1

I am trying to remove columns, from data frame say a, of whose names are present in array, say x.

a <- data.frame( ab = 1:3, ac = 4:6, ad = 7:9, ae = 10:12, af = 13:15, ag=c("a", "b", "c"))

x <- c("ac", "ad", "ae")

Here, I want to remove columns from data frame a whose names are present in array x.

I have tried following but in vain:

for (i in 1:length(x))
{
 y <- a[, -grep(x[i],colnames(a))]
}

Can any one help me in this aspect?

Regards,

Mandy

0

2 Answers 2

4

One simplest solution would be

newA = a[,setdiff(colnames(a),x)]
Sign up to request clarification or add additional context in comments.

1 Comment

worked magically.. Thanks vrajs5.
3

If you want to destructively remove them from your data.frame, you can use list(NULL), like this:

a
#   ab ac ad ae af ag
# 1  1  4  7 10 13  a
# 2  2  5  8 11 14  b
# 3  3  6  9 12 15  c

a[x] <- list(NULL)
a
#   ab af ag
# 1  1 13  a
# 2  2 14  b
# 3  3 15  c

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.