[R] Use paste function to select column of data

David Winsemius dwinsemius at comcast.net
Wed May 18 21:22:32 CEST 2011


On May 18, 2011, at 3:12 PM, John Poulsen wrote:

> Hello,
>
> I want to build a function to call up a column of a data.frame by  
> the names of the columns.  I have column names that are sequentially  
> named (col1, col2, etc.). How do I change a character expression  
> into something that will be understood as a data.frame column.  For  
> example:
>
> example<-data.frame(cbind(col1=1:10, col2=21:30, col3=41:50))
>  call.fun<-function(t){
>    x<-paste("col",t, sep="")  ## Change this so that it is the data,  
> not a character expression
# right.... don't use the "$" operator, instead  use "[["
         example[[x]]    }
>
> call.fun(t=2)
>
> Within the real function, I will continue do calculations on the  
> column of data.  My problem is that I am either getting a character  
> expression or NULL from my function.
>
> Thanks for your help on what is probably a very simple question.
>
> John

-- 

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list