简体   繁体   English

R-将数据帧拆分为向量,并将所有向量作为不同的参数传递给同一函数

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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