1

I'm not quite familiar with R function dealing with variables used. Here's the problem:

I want to built a function, of which variables ... are column names of data frame used for table().

f <- function (data, ...){
    T <- with(data, table(...)  # ... variables input
    return(T)
}

How can I deal with the code? Thanks a lot for answering!

leoluyi
  • 852
  • 1
  • 7
  • 14

2 Answers2

1

The order of evaluation doesn't quite work right with with() apparently. Here's an alternative that should work (using sample data from @DavidArenburg)

set.seed(1)
data1 <- data.frame(a = sample(5,5), b = sample(5,5))

f <- function (data, ...) {
    xx <- lapply(substitute(...()), eval, data, parent.frame())
    T <- do.call(table, xx)
    return(T)
}

f(data = data1, a,b)
MrFlick
  • 178,638
  • 15
  • 253
  • 268
0

It is often far easier to avoid non-standard evaluation and use character strings to reference the columns within a data.frame.

set.seed(1)
data1 <- data.frame(a = sample(5,5), b = sample(5,5))

f <- function (data, ...) {
    do.call(table,data[unlist(list(...))])

}
# the following calls to `f` return the same results
f(data = data1, 'a','b')
f(data = data1, c('a','b'))
a <- c('a','b')
f(data = data1, a)
mnel
  • 110,110
  • 27
  • 254
  • 248