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

mandy-jubl
  • 77
  • 1
  • 7

2 Answers2

4

One simplest solution would be

newA = a[,setdiff(colnames(a),x)]
vrajs5
  • 4,066
  • 1
  • 27
  • 44
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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485