[R] character substitution within a variable name
Duncan Murdoch
murdoch.duncan at gmail.com
Wed Nov 23 20:58:03 CET 2011
On 23/11/2011 2:29 PM, matric wrote:
> Hi,
> I'd like to create a function that accepts as arguments a string that is to
> be substituted within a variable name. For instance, suppose I have a data
> frame df:
>
> df<-data.frame(x_narrow=c(rnorm(100,0,1)),x_wide=c(rnorm(100,0,10)))
>
> What I have in mind is something like:
>
> f<- function(string){
> var = paste("x_",string,sep = "")
> df$var
> }
>
> which does not work. Any suggestion for modifications? Thanks in advance,
For indexing a dataframe, use the name as the column index:
df[, var]
will work.
Duncan Murdoch
More information about the R-help
mailing list