使用改变参数的lapply

Mat*_*ert 8 r lapply

R教科书继续推广使用lapply而不是循环.即使对于带有参数的函数,这也很容易

lapply(somelist, f, a=1, b=2) 
Run Code Online (Sandbox Code Playgroud)

但是如果参数根据列表元素而改变怎么办?假设我的名单包括:

somelist$USA
somelist$Europe
somelist$Switzerland
Run Code Online (Sandbox Code Playgroud)

加上有anotherlist相同的地区,我想用这些不断变化的论点来讨价还价?例如,当f是比率计算时,这可能是有用的.

lapply(somelist, f, a= somelist$USA, b=anotherlist$USA) 
Run Code Online (Sandbox Code Playgroud)

是否有方法可以有效地运行这些区域?

编辑:我的问题似乎是我试图使用以前编写的函数没有索引...

ratio <-function(a,b){
z<-(b-a)/a
return(z)
}
Run Code Online (Sandbox Code Playgroud)

这导致了

lapply(data,ratio,names(data))
Run Code Online (Sandbox Code Playgroud)

这不起作用.也许其他人也可以从这个错误中吸取教训

Vin*_*ent 16

应用列表名称而不是列表元素.例如:

somelist <- list('USA'=rnorm(10), 'Europe'=rnorm(10), 'Switzerland'=rnorm(10))
anotherlist <- list('USA'=5, 'Europe'=10, 'Switzerland'=4)
lapply(names(somelist), function(i) somelist[[i]] / anotherlist[[i]])
Run Code Online (Sandbox Code Playgroud)

编辑:

您还会问"是否有"循环方式"有效"地执行此操作.您应该注意,申请不一定更有效.效率可能取决于你的内在功能有多快.如果要对列表的每个元素进行操作,则需要一个循环,无论它是否隐藏在apply()调用中.检查这个问题:R是否适用于家庭而不是语法糖?

我上面给出的例子可以重写为for循环,你可以做一些天真的基准测试:

fun1 <- function(){
    lapply(names(somelist), function(i) somelist[[i]] / anotherlist[[i]])
}
fun2 <- function(){
    for (i in names(somelist)){
        somelist[[i]] <- somelist[[i]] / anotherlist[[i]] 
    }
    return(somelist)
}
library(rbenchmark)

benchmark(fun1(), fun2(),
          columns=c("test", "replications",
          "elapsed", "relative"),
          order="relative", replications=10000)
Run Code Online (Sandbox Code Playgroud)

我机器上基准测试的输出是这样的:

    test replications elapsed relative
1 fun1()        10000   0.145 1.000000
2 fun2()        10000   0.148 1.020690
Run Code Online (Sandbox Code Playgroud)

虽然这不是一个真正的工作应用程序,并且功能不是现实的任务,但您可以看到计算时间的差异可以忽略不计.


Rei*_*son 7

你只需要弄清楚要做什么lapply().在names()我们重写f()以采用不同的参数之后,这里的列表就足够了:

somelist <- list(USA = 1:10, Europe = 21:30,
                 Switzerland = seq(1, 5, length = 10))
anotherlist <- list(USA = list(a = 1, b = 2), Europe = list(a = 2, b = 4),
                    Switzerland = list(a = 0.5, b = 1))

f <- function(x, some, other) {
    (some[[x]] + other[[x]][["a"]]) * other[[x]][["b"]]
}

lapply(names(somelist), f, some = somelist, other = anotherlist)
Run Code Online (Sandbox Code Playgroud)

赠送:

R> lapply(names(somelist), f, some = somelist, other = anotherlist)
[[1]]
 [1]  4  6  8 10 12 14 16 18 20 22

[[2]]
 [1]  92  96 100 104 108 112 116 120 124 128

[[3]]
 [1] 1.500000 1.944444 2.388889 2.833333 3.277778 3.722222 4.166667 4.611111
 [9] 5.055556 5.500000
Run Code Online (Sandbox Code Playgroud)