Hi:
Hi:

Observe that if you quote the name of the variable in your original
function,
everything is fine; in fact, you can ask for multiple variables.

> k <- function(df, col) df[col]
> k(testdata, 'var1')
        var1
1 0.91663902
2 0.60470753
3 0.09599891
> k(testdata, 'censor')
  censor
1      0
2      0
3      0
> k(testdata, c('start', 'stop'))
  start stop
1     0    1
2     1    2
3     2    3

However, if you use the deparse/substitute trick, it works, but only
for a single variable:

k2 <- function(df, col) df[deparse(substitute(col))]
> k2(testdata, var1)
        var1
1 0.91663902
2 0.60470753
3 0.09599891
> k2(testdata, start)
  start
1     0
2     1
3     2
> k2(testdata, c(start, stop))
Error in `[.data.frame`(df, deparse(substitute(col))) :
  undefined columns selected

and the same error is returned if the variables are quoted.

HTH,
Dennis

On Fri, Feb 12, 2010 at 11:01 AM, Philipp Rappold <philipp.rappold@gmail.com
> 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.
>
> 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
>
>
> ______________________________________________
> R-help@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.
>

	[[alternative HTML version deleted]]

