You cannot do this subset with $ . In the source code ( R/src/main/subset.c ), it indicates:
/ * The $ subset operator.
We must necessarily evaluate only the first argument.
The second will be a symbol that must be matched, not evaluated.
* /
Second argument? What kind?! You must understand that $ , like everything else in R (including, for example, ( , + , ^ , etc.), is a function that takes arguments and evaluates. df$V1 can be rewritten as
`$`(df , V1)
or really
`$`(df , "V1")
But...
`$`(df , paste0("V1") )
... for example, it will never work, and nothing else should be evaluated first in the second argument. You can only pass a string that is never evaluated.
Instead, use [ (or [[ if you want to extract only one column as a vector).
For example,
var <- "mpg"
You can do the ordering without loops using do.call to build an order call. The following is a reproducible example:
# set seed for reproducibility set.seed(123) df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )
Simon O'Hanlon Aug 14 '13 at 9:57 on 2013-08-14 09:57
source share