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
  • 942
  • 1
  • 7
  • 14
  • `f <- function(data, vectorofcolumnnames) table(data[, vectorofcolumnnames])` – Roland Jun 16 '14 at 10:53
  • Thanks for help! I'm just curious about how `...` works as a list in the function. And in what circumstances I should use `...` ? – leoluyi Jun 16 '14 at 13:28
  • Have you studied section 10.4 of An Introduction to R? – Roland Jun 16 '14 at 13:31
  • Yes. But I still can't figure it out why arguments can't be used like this? `f <- function (data, ...){ T <- with(data, table(...)) return(T) } ` Thank you for the patience in answering a beginners question – leoluyi Jun 16 '14 at 14:04
  • 1
    Worth reading http://stackoverflow.com/questions/3057341/how-to-use-rs-ellipsis-feature-when-writing-your-own-function – mnel Jun 17 '14 at 02: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
  • 195,160
  • 17
  • 277
  • 295
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
  • 113,303
  • 27
  • 265
  • 254