I am trying to remove columns from data.frame. The following expression works
a1$"STR_COL_4_" <- NULL
but
xx <- "STR_COL_4_"
a1$xx <- NULL
does not work...what is the problem ???
I am trying to remove columns from data.frame. The following expression works
a1$"STR_COL_4_" <- NULL
but
xx <- "STR_COL_4_"
a1$xx <- NULL
does not work...what is the problem ???
As Richard Scriven, user20650, and agenis have pointed out, when you use $
to refer to a column in a data frame, it merely looks for that column in the data frame. In your second example, R looks for a column named xx
and fails, even though there is already a variable named xx
. Using [[ ]]
lets R evaluate an expression.
As an example using the builtin cars dataset:
> data(mtcars)
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
> var <- "wt"
> mtcars$var
NULL
> mtcars[[var]]
[1] 2.620 2.875 2.320 3.215 3.440 3.460 3.570 3.190 3.150 3.440 3.440 4.070
[13] 3.730 3.780 5.250 5.424 5.345 2.200 1.615 1.835 2.465 3.520 3.435 3.840
[25] 3.845 1.935 2.140 1.513 3.170 2.770 3.570 2.780