2

Let's introduce two functions:

test_f <- function(df, var) {
  print(df$var)
}

test_s <- function(df, var) {
  print(df[, var])
}

And the df itself:

df <- data.frame(c(0:10))
colnames(df) <- "X"

What I'm missing when running, the $ version returns NULL, but [] prints the result correctly:

> test_f(df, "X")
NULL
> test_s(df, "X")
 [1]  0  1  2  3  4  5  6  7  8  9 10
m0nhawk
  • 22,980
  • 9
  • 45
  • 73

1 Answers1

4

Using the [ approach has its advantages, among which are being able to easily specify both the rows and columns you want (note the use of plural there) and being able to use the same syntax for a data.frame or a matrix.

If you wanted to make your function work, you would have to use eval(parse(...)) to help R figure out what exactly you want to extract.

Here's an example:

test_f <- function(df, var) {
  a <- deparse(substitute(df))
  b <- deparse(substitute(var))
  Get <- paste(a, b, sep = "$")
  eval(parse(text = Get))
}
test_f(df, X)
#  [1]  0  1  2  3  4  5  6  7  8  9 10
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485