将函数应用于列表的每个元素和两个数据框的每一行

Apply a function to each element of a list and each row of two data frames

是否有针对此的 "apply" 应用程序,而不是在 base R 中对两个数据帧的每一行进行双循环(不使用包)?

listD <- matrix(1:6, ncol=2)
listD <- split(listD,seq(NROW(listD)))
df1 <- data.frame(x=c(1,2), y=c(3,4))
df2 <- data.frame(x=c(3,2), y=c(1,1))
testFunc <- function(a, b, c) a * (b + c)

for (j in 1:nrow(df1)) {
  for (s in 1:nrow(df2)) {
     print(lapply(listD, FUN= testFunc, b=df1[j,], c=df2[s,]))
  }
}

谢谢!

使用 outer 的副作用:

invisible(outer(as.matrix(df1), as.matrix(df2), FUN = Vectorize(function (b, c) {
  print(lapply(listD, testFunc, b, c))
  NULL
})))

我不知道这是否是对您的 for 循环的改进。有一个流言说必须不惜一切代价避免 R 中的 for 循环(也许它们看起来太简单了?)