[R] how to use a column name from the data frame in the function

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Fri Aug 23 06:49:13 CEST 2013


Please don't post in HTML format... it messes with code examples.

Use character indexing (please read the Introduction to R... again if necessary).

myf <- function(df, colname){
  df[ ,colname ]
}

colname  <- "a"
myf(m,colname)

Until you learn simple R syntax, I strongly recommend avoiding writing tricky code that plays with names of variables.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

song song <rprojecthelp at gmail.com> wrote:
>for example I have data frame m as below:
>
>m=as.data.frame(outer(1:5,6:9))
>colnames(m)=c('a','b','c','d')
>
>and I define the function
>
>myf=function(df, colname){
>
>   suppose colname is a, then:
>   how can I get the column 'a'
>   and how to get the colname as a string, 'a'
>
>}
>
>Thank you!
>
>	[[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