0

Could anyone please explain to me why the following function call returns 'NULL' instead of 1?

> df <- data.frame(1,2,3)
> df
  X1 X2 X3
1  1  2  3
> f <- function(vdf, vx) { return (vdf$vx); }
> f(df, "X1")
NULL
> 
stathisk
  • 234
  • 3
  • 12
  • 1
    You could try `f <- function(vdf, vx) {vdf[,vx]}; f(df, "X1")` instead, but it seems that I don't know why your code isn't working – David Arenburg May 06 '14 at 21:06
  • 2
    It happens for the same reason that `col="X1";df$col` returns NULL. R position matches `"X1"` to the argument `vx` and `$` does not evaluate its argument so the function is searching for `df$vx` regardless of the value you assign to the argument `vx`. – Simon O'Hanlon May 06 '14 at 21:09
  • [**Here's a bit more info**](http://stackoverflow.com/a/18228613/1478381) and another example. – Simon O'Hanlon May 06 '14 at 21:11
  • Thanks folks. Should I delete it ? – stathisk May 06 '14 at 21:28

0 Answers0