4

I have created a data frame named z.

  a = c(1,1,1);
  b = c(2,2,2);
  c = c(3,3,3);
  d = c(4,4,4);
  z = data.frame(a,b,c,d);

I want to remove column c and d from data frame z.

I tried this code

p = subset(z , colnames(z) == c('a' , 'b'))

But i am getting this result

a   b   c   d
1   2   3   4   
1   2   3   4 

What changes should i make in this command to remove column c and d from z.

zx8754
  • 42,109
  • 10
  • 93
  • 154
Nikhil Singhal
  • 69
  • 1
  • 1
  • 2
  • 3
    `z[, c('a', 'b')]` – Jaap Aug 23 '17 at 17:53
  • 2
    Or argument `select`: `subset(z, select = c('a' , 'b'))`. BTW, why the semi-colon at the end of instructions? `R` is not the C language, the semi-colon separates instructions so when youend an instruction line with it, you are in fact separating it from the end, the NULL instruction. – Rui Barradas Aug 23 '17 at 17:55
  • 2
    @ycw updated :-) – Jaap Aug 23 '17 at 17:58

1 Answers1

9

We can use the following to specify which columns to select by names.

z[, c("a", "b")]

This also works.

z[c("a", "b")]

Or we can use the following to first specify which columns to remove in a vector, and then select the columns not in that vector.

cols_remove <- c("c", "d")
z[, !(colnames(z) %in% cols_remove)]
www
  • 35,154
  • 12
  • 33
  • 61