简体   繁体   中英

R - Splitting dataframe into vectors and passing all of them as different arguments to same function

I have a function that takes as many "data vector" inputs as desired, and performs operations on all of them together. So following works:

myFunction( df[,1], df[,2], df[,3], ..up to the number of columns.. )

I would like to split a data frame (or matrix) into different column vectors and supply all of them as different inputs (basically example above without having to write the each column one by one)

I have already tried to following:

myFunction( split( df, col(df) ) )

and this doesn't work because the function I am trying to use does not accept list of inputs, it expects each of them to be a different argument.

Is there a way to do this?

Working example of what is suggested in the comments:

argumentList <- split(df, col(df)) # create a list of arguments
names(argumentList)[1] <- "x" # name at least one of the inputs for the default value x 
argumentList["na.rm"] <- TRUE # add any other arguments needed
do.call( myFunction, argumentList )

The question seems to be ambiguous a little. That said, the following covers the things mentioned in the question to a great extent.

set.seed(1)
df <- as.data.frame(matrix(c(rep(rnorm(10),5)), ncol=5, byrow=TRUE))
df
sum(df[,1], df[,2], df[,3], df[,4], df[,5])      # 6.610139
sum(unlist(lapply(as.matrix(1:ncol(df)), function(i) {df[,i] }))) # 6.610139

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM