Claude
Claude

Reputation: 1784

Dynamically select column from data frame in function

I have a data frame from which I want to select a column. For that purpose I have defined a function. The name of the column is provided as parameter:

d <- data.frame(x = 1:10, y = sample(1:100, 10, replace = TRUE))

f1 <- function(data, name)
{
  data[name]
}

f1(d, "x")
f1(d, "y")

However, instead of providing the column name as character string I would like to provide the column as symbol as in this form:

f2(d, x)
f2(d, y)

My question: How is f2 to be defined?

Background: This is a simplified example. Actually the function to be defined has this prototype:

fx(d, v, ...)

and returns a data frame which sums upv over any column listed in ....

Upvotes: 1

Views: 3020

Answers (1)

gagolews
gagolews

Reputation: 13056

Use deparse(substitute(name)), i.e.

f2 <- function(data, name)
    data[deparse(substitute(name))]

For example:

data <- data.frame(id=1:5, val=letters[1:5])
f2(data, val)
##  val
##1   a
##2   b
##3   c
##4   d
##5   e

For multiple columns selection you may use:

f3 <- function(data, ...) {
   cols <- sapply(as.list(match.call())[-(1:2)], as.character)
   data[cols]
}

Which gives e.g.:

f3(data, val, id)
##   val id
## 1   a  1
## 2   b  2
## 3   c  3
## 4   d  4
## 5   e  5

Upvotes: 2

Related Questions