1

Please note that I already had a look at this and that but still cannot solve my problem.

Suppose a minimal working example:

a <- c(1,2,3)
b <- c(2,3,4)
c <- c(4,5,6)
dftest <- data.frame(a,b,c)

foo <- function(x, y, data = data) {
    data[, c("x","y")]
    }
foo(a, b, data = dftest)

Here, the last line obviously returns an Error: undefined columns selected. This error is returned because the columns to be selected are x and y, which are not part of the data frame dftest.

Question: How do I need to formulate the definition of the function to obtain the desired output, which is

> dftest[, c("a","b")]
#   a b
# 1 1 2
# 2 2 3
# 3 3 4

which I want to obtain by calling the function foo.

Please be aware that in order for the solution to be useful for my purposes, the format of the function call of foo is to be regarded fixed, that is, the only changes are to be made to the function itself, not the call. I.e. foo(a, b, data = dftest) is the only input to be allowed.

Approach: I tried to use paste and substitute in combination with eval to first replace the x and y with the arguments of the function call and then evaluate the call. However, escaping the quotation marks seems to be a problem here:

foo <- function(x, y, data = data) {
    substitute(data[, paste("c(\"",x,"\",\"",y,"\")", sep = "")])
    }
foo(a, b, data = dftest)    
eval(foo(a, b, data = dftest))

Here, foo(a, b, data = dftest) returns:

dftest[, paste("c(\"", a, "\",\"", b, "\")", sep = "")]

However, when evaluating with eval() (focusing only on the paste part),

paste("c(\"", a, "\",\"", b, "\")", sep = "")

returns:

# "c(\"1\",\"2\")" "c(\"2\",\"3\")" "c(\"3\",\"4\")"

and not, as I would hope c("a","b"), thus again resulting in the same error as above.

Community
  • 1
  • 1
iraserd
  • 669
  • 1
  • 8
  • 26

1 Answers1

2

Try this:

foo <- function(x, y, data = data) {
    x <- deparse(substitute(x))
    y <- deparse(substitute(y))
    data[, c(x, y)]
}
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thank you! Everyday there is a new function to discover in R ... ! Still, it can be a bit disencouraging when you get an answer on SO within a few minutes on a question you have been trying to solve yourself for an hour... :/ – iraserd Apr 14 '14 at 14:17
  • @rawr, did you try that option? – A5C1D2H2I1M1N2O1R2T1 Apr 14 '14 at 15:08