簡體   English   中英

R-將數據幀拆分為向量,並將所有向量作為不同的參數傳遞給同一函數

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

我有一個函數,它可以根據需要接收盡可能多的“數據向量”輸入,並一起對所有輸入執行操作。 因此,以下工作:

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

我想將數據幀(或矩陣)拆分為不同的列向量,並將它們全部作為不同的輸入提供(基本上是上面的示例,而不必一一寫入每一列)

我已經嘗試遵循:

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

這是行不通的,因為我要使用的函數不接受輸入列表,它希望每個輸入都是不同的參數。

有沒有辦法做到這一點?

評論中建議的工作示例:

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 )

這個問題似乎有點模棱兩可。 也就是說,以下內容將在很大程度上涵蓋問題中提到的內容。

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