8

I have the following dataframe:

a b   c   d   e      
1 rr  dfv 5   0.1
9 t   rr1 222 0.44
7 sdf we  1   0.111

I want to select all columns except say d and e. I know I can use subset for this: subset(df, -c(d, e)) Why can't I do df[,-c(d,e)]?

Please advise.

P.S @sotos and others:

x[,-c("b", "c")] Error in -c("b", "c") : invalid argument to unary operator

Dr. Richard Tennen
  • 267
  • 1
  • 2
  • 9
  • For some reason it didn't work, maybe it depends on the R version. – Dr. Richard Tennen Nov 07 '17 at 08:30
  • x[,-c("b", "c")] Error in -c("b", "c") : invalid argument to unary operator – Dr. Richard Tennen Nov 07 '17 at 08:37
  • @sotos please review again, what is wrong? – Dr. Richard Tennen Nov 07 '17 at 08:37
  • 1
    Nothing wrong. It is just a duplicate. Go through the link and you will find the solution very easily. Also have in mind that questions about "What is wrong with my code" and "Why isn't my code working" are outside the scope of SO – Sotos Nov 07 '17 at 08:39
  • I am following @AleksandrVoitov solution and it didn't work. Please provide me with the link, I don't see any link here. Sorry if it's duplicate didn't find the question before asking mine. – Dr. Richard Tennen Nov 07 '17 at 08:40
  • 1
    At the top of your question. – Sotos Nov 07 '17 at 08:42
  • @Sotos I have checked the link you provided and still didn't answer my question why df[, -c("a","b")] won't work? They use which and subset there but not what I am asking for. – Dr. Richard Tennen Nov 07 '17 at 08:42
  • Read my comment above about "Why isn't my code working". Of course in your case, It doesn't work simply because it is the wrong syntax. – Sotos Nov 07 '17 at 08:43
  • @Sotos would you be so kind and tell me what is wrong please? – Dr. Richard Tennen Nov 07 '17 at 08:46
  • 1
    Simply wrong syntax. You can call it by name directly (i.e. `iris['Species']`) but to exclude a column the minus sign will not work. You need to specify it by calling the `names` (column names) of your data frame and excluding (via `!` and `%in%`) the ones you want to remove – Sotos Nov 07 '17 at 08:49
  • 3
    R try to evaluate -c("a", "b") which translate to do negative of string "a" and string "b". -ve of string doesn't make sense in usual R syntax. You can check this by typing -"a" in the R prompt same error will happen. – Kushdesh Nov 07 '17 at 08:54
  • Does not work unless you add "select" subset(df, select=c(-c(d,e))) – Isaac Zhao Jun 03 '20 at 04:57

0 Answers0