[R] Access dataframe with variable name in function

Sharpie chuck at sharpsteen.net
Fri Feb 12 21:50:40 CET 2010



Philipp Rappold wrote:
> 
> Sorry guys, but I have another one:
> 
> 
> I want to write a function that returns a certain column of a 
> dataframe. The function accepts two argument: the dataframe and the 
> name of the column, but the column is not given as a "string" but as 
> a variable name.
> 
> k <- function(df, col) df[col]
> 
> 

You can do this by using deparse(substitute()) to coerce the variable to a
character string:

  k <- function(df, col){
    return( df[ deparse(substitute(col)) ] )
  }

testData <- data.frame( foo = 1:3, bar = LETTERS[1:3] )

k( testData, bar )

  bar
1   A
2   B
3   C

Hope this helps!

-Charlie
-- 
View this message in context: http://n4.nabble.com/Access-dataframe-with-variable-name-in-function-tp1490389p1490410.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list