Skip to content
Prev 254 / 585 Next

converting string to a object name of a dataset

On Mar 18, 2011, at 3:19 AM, BXC (Bendix Carstensen) wrote:

            
Many R users make an effort to avoid using `attach` in any setting  
other than the very earliest efforts at learning R. As a result they  
also avoid the use of "$" in coding, since it is much less flexible  
than the function on which it depends, namely "[[". If you want the  
string "x" to beinterpreted as a columnname then "[[" is the way to go:

 > data1<- data.frame(x=c(1:4), y=rep(1,4))
 > gvars<- c("x", "y")

#Two methods get you the results you want:

 > data1[[gvars[1] ]]
[1] 1 2 3 4
 > get("data1")[[ gvars[1] ]]
[1] 1 2 3 4