1

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 ....

1
  • @Arun call to aggregate whith parameter by=<...> und function sum. Commented Apr 30, 2014 at 13:58

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.