Removing columns with brackets in R doesn't work

Viewed 106

I have a data frame:

ID    user    study    var   varb   varc   varf
101   a       b         3     4      3       4
102   b       a         4     5      5       6
103   g       a         4     4      5       6
104   b       c         6     7      7       5

I am trying to remove the first three columns by using the index positions

df <- df[-c(1:3)]

I was sure this method worked to remove columns. In fact, the first time I ran this line it did work as expected but now all it does is remove the rows instead of columns. Now, I'm just using the subset() method to remove columns which works fine. But, I want to brush up on my R since I have gotten rusty after not writing in it for so long. Where did I go wrong with the original method I was using before?

1 Answers

If it is a data.table, we may need

df[, -c(1:3), with = FALSE]

Or perhaps use select from dplyr

library(dplyr)
df %>%
    select(-(1:3))
Related