13

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.

3
  • 3
    z[, c('a', 'b')] Commented Aug 23, 2017 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. Commented Aug 23, 2017 at 17:55
  • 2
    @ycw updated :-) Commented Aug 23, 2017 at 17:58

1 Answer 1

24

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)]
Sign up to request clarification or add additional context in comments.

9 Comments

keeps <- c("a, "b") DF[keeps]
@Sateesh Your comment is unclear. It is not reproducible. What do you want to achieve?
@Sateesh Is this R code?
@Sateesh You have not responded my question. What is the purpose of your comment? Is your code really working in R?
yes it works...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.