r - 如何使用lapply定义多个变量?

标签 r function variables lapply

我想将具有多个具有不同值的变量的函数应用于列表。我知道如何用一个不断变化的变量来做到这一点

sapply(c(1:10), function(x) x * 2)
# [1]  2  4  6  8 10 12 14 16 18 20

但不是两个。我首先手动向您展示我想要的(实际上我使用 lapply()sapply() 在 SO 中更概括):
# manual
a <- sapply(c(1:10), function(x, y=2) x * y)
b <- sapply(c(1:10), function(x, y=3) x * y)
c <- sapply(c(1:10), function(x, y=4) x * y)
c(a, b, c)
# [1]  2  4  6  8 10 12 14 16 18 20  3  6  9 12 15 18 21 24 27 30  4  8 12 
# [24]  16 20 24 28 32 36 40

这是我尝试定义 x 的尝试和 y .
# attempt
X <- list(x = 1:10, y = 2:4)
sapply(c(1:10, 2:4), function(x, y) x * y)
# Error in FUN(X[[i]], ...) : argument "y" is missing, with no default

解决方案基准
library(microbenchmark)
microbenchmark(sapply = as.vector(sapply(1:10, function(x, y) x * y, 2:4)), 
               mapply = mapply( FUN = function(x, y) x * y, 1:10, rep( x = 2:4, each = 10)),
               sapply2 = as.vector(sapply(1:10, function(y) sapply(2:4, function(x) x * y))),
               outer = c(outer(1:10, 2:4, function(x, y) x * y)))
# Unit: microseconds
# expr        min       lq      mean   median       uq      max neval
# sapply   34.212  36.3500  62.44864  39.1295  41.9090 2304.542   100
# mapply   62.008  65.8570  87.82891  70.3470  76.5480 1283.342   100
# sapply2 196.714 203.9835 262.09990 223.6550 232.2080 3344.129   100
# outer     7.698  10.4775  13.02223  12.4020  13.4715   53.883   100

最佳答案

使用 mapply()

mapply() 将函数应用于多个列表或向量参数。

rep() 还用于重复值 2、3 和 4。在 each 中指定 10参数,rep()重复 x 的每个元素10倍。

这是必要的,因为 mapply() 中的第一个参数- 1:10 - 长度为 10。

# supply the function first, followed by the
# arguments in the order in which they are called in `FUN`
mapply( FUN = function(x, y) x * y
        , 1:10
        , rep( x = 2:4, each = 10)
)

# [1]   2  4  6  8 10 12 14 16 18 20  3  6  9 12 15 18 21 24 27 30  4  8 12 16 20
# [26] 24 28 32 36 40

关于r - 如何使用lapply定义多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598687/

相关文章:

r - 为 Shiny 的应用程序创建动态输入字段

r - 在 macOS 上设置 rstudio-server

r - 使用 dplyr mutate 将列名传递给函数,而不使用折旧的 mutate_

java - 为什么我得到空数组?

javascript - 在 Ruby 中动态命名数组/哈希

c++ - 对工作程序中自定义函数的 undefined reference (C++ 和 RcppParallel)

r - 检查一个向量中的值是否小于另一向量(不同长度)中的值,并用 Y/N 答案填充表格

arrays - bash $FUNCNAME 数组没有被清除

function - Tkinter 在类中调用函数

java - 函数内的多线程变量访问