[R] use list as function arguments
Alexander Shenkin
ashenkin at ufl.edu
Thu May 24 17:32:54 CEST 2012
Hello Folks,
Is there any way to pass a list into a function such that the function
will use the list as its arguments? I haven't been able to figure that out.
The background: I'm trying to build a function that will apply another
function multiple times, each time with a different set of specified
arguments. I'm trying to figure out how to pass in a list of argument
lists, then loop through the top-level list, passing in the lower-level
list as function arguments.
pseudocode:
b = list( list( arg1 = 1, arg2 = 2 ),
list( arg1 = 3, arg2 = 4 )
)
a <- apply_function(arglist) {
for (i in length(arglist)) {
b(arglist[i])
}
}
Specifically, the actual use I'm trying to implement is a function to
format columns of data frames and matrices independently. What I have
so far is below, but it's not working. Perhaps I'm going about this the
wrong way?
format_cols <- function(x, format_list = list()) {
# usage: length(format_list) must equal ncol(x)
# format list should be a list of lists of key=value pairs
corresponding to format settings for each column
if (is.data.frame(x)) {
newout = data.frame()
} else if (is.matrix(x)) {
newout = matrix()
}
for (i in 1:ncol(x)){
newout = cbind(newout, format(x,format_list[[i]]))
x[,i] = format(x,format_list[[i]])
}
return(newout)
}
Thanks,
Allie
More information about the R-help
mailing list