1

Is there a reason why in R the following logic does not work? Using mtcars dataset:

> mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1

Wanting column mpg:

> mtcars[,c("mpg")]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9
[21] 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4

Not wanting column mpg:

> mtcars[,-c("mpg")]
Error in -c("mpg") : invalid argument to unary operator

Same with:

mtcars[,1:2] vs mtcars[,-1:2].

Helen
  • 533
  • 12
  • 37
  • 1
    It isn't straight forward with names. You got to do `mtcars[!names(mtcars) %in% "mpg"]` or with more than 1 indexes `mtcars[-c(1, 2)]` – Ronak Shah Jun 03 '18 at 09:52
  • Ok, thanks! I'm just wondering if there is a reason, not *how* to do it :) – Helen Jun 03 '18 at 09:55
  • Reopened the question. In case for future readers , if they want to know how to do it. https://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame – Ronak Shah Jun 03 '18 at 09:58
  • 3
    `-c("mpg")` is evaluated, and it triggers an error,just as it would if you typed it directly to your console, because characters can't be negated. – moodymudskipper Jun 03 '18 at 10:06
  • I see, that makes it a little more clear, thank you! – Helen Jun 03 '18 at 10:07
  • 2
    `mtcars[,-(1:2)]` works, you are probably confused about operator precedence. `-1:2` is `c(-1,0,1,2)`, and you can't use both negative and positive indices to subset – moodymudskipper Jun 03 '18 at 10:09
  • Ah, of course! Thank you very much! :) – Helen Jun 03 '18 at 10:10

0 Answers0