[R] Use paste function to select column of data

Peter Ehlers ehlers at ucalgary.ca
Wed May 18 21:22:13 CEST 2011


On 2011-05-18 12:12, 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
>       example$x}
>
> call.fun(t=2)

Get out of the dollar habit.
Replace your

   example$x

with

   example[[x]]

or with

   example[, x]

Peter Ehlers

>
>   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
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list