[R] Access dataframe with variable name in function

Philipp Rappold philipp.rappold at gmail.com
Fri Feb 12 20:01:48 CET 2010


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.

EXAMPLE
----------------------

 > testdata
   start stop censor groupvar       var1      var2
1     0    1      0        1 0.91663902 0.0847912
2     1    2      0        1 0.60470753 0.6487798
3     2    3      0        1 0.09599891 0.2195178
x

k <- function(df, col) df[col]

EXPECTED RESULTS
-------------------------------------
k(testdata, var1) should return the same output as testdata["var1"], 
which is

         var1
1 0.91663902
2 0.60470753
3 0.09599891
4         NA
5 0.07747445
6 0.44608030
7 0.77317152

Note that I want to use k(testdata, var1) instead of k(testdata, 
"var1").

Thanks for your help!
All the best
Philipp



More information about the R-help mailing list