使用变量数组作为 R 函数的迭代输入,无需 for 循环

问题描述 投票:0回答:2

我正在尝试使用数组将所有变量输入函数 K 次。 这是一个简单的例子:

set.seed(707)

Func<-function(a,b,c,d,e,f,g,h,i,j){
  temp <- a+b+c+d+e+f+g+h+i+j
  return(temp)
}

K <- 3
library(lhs)
A <- randomLHS(10,K)

> A
            [,1]       [,2]      [,3]
 [1,] 0.71223229 0.62418246 0.3933959
 [2,] 0.01531924 0.06501699 0.7463748
 [3,] 0.85278795 0.19983286 0.1856308
 [4,] 0.28234183 0.32716120 0.6706615
 [5,] 0.11708063 0.74196491 0.8515147
 [6,] 0.33521099 0.45473874 0.9173855
 [7,] 0.97812812 0.57400252 0.4987922
 [8,] 0.53003009 0.94340463 0.0293076
 [9,] 0.49162910 0.84928499 0.2309974
[10,] 0.69963290 0.26794110 0.5024444

我想迭代地将每一列提供给函数

Func
,然后合并结果。我能想到的最佳解决方案依赖于 for 循环和索引,但我想知道是否有更好的方法来使用 apply 来做到这一点:

Out <- NULL
for(i in 1:K){
test <- do.call(what = Func, args = as.list(A[,i]))
Out <- c(Out,test)
}

为了确保它按照我的想法工作,我只是比较:

Out
colSums(A)

> Out
[1] 5.014393 5.047530 5.026505
> colSums(A)
[1] 5.014393 5.047530 5.026505
r for-loop apply do.call
2个回答
0
投票

您可以转置

A
并使用
as.data.frame()
进行转换,然后使用
purrr::pmap
,这将按行工作

purrr::pmap(unname(as.data.frame(t(A))), Func)

输出:

[[1]]
[1] 5.014393

[[2]]
[1] 5.04753

[[3]]
[1] 5.026505

0
投票
Out <- apply(A, 2, FUN = \(x) do.call(Func, args = as.list(x)))

microbenchmark::microbenchmark(loop = {
Out <- NULL
for(i in 1:K){
  test <- do.call(what = Func, args = as.list(A[,i]))
  Out <- c(Out,test)
}
},
apply = {Out <- apply(A, 2, FUN = \(x) do.call(Func, args = as.list(x)))}
)
#Unit: microseconds
#  expr    min      lq     mean median      uq     max neval
#  loop 2465.3 2522.10 2833.954 2625.7 2797.00 13389.8   100
# apply   35.7   39.75   64.778   48.7   53.65  1657.5   100
© www.soinside.com 2019 - 2024. All rights reserved.