以下lapply
将列表中的每个元素乘以2
lapply(1:5, function(x, y) x * y, y = 2)
是否可以使用lapply
为列表中的每个元素指定不同的y
?以下伪代码是一个示例:
lapply(1:5, function(x, y) x * y, y = 1 if x is odd and = 2 if x is even)
答案 0 :(得分:2)
sapply
和lapply
仅允许一个不同的参数。如果您有多个,则可以使用mapply
或Map
。例如
x<-1:5
mapply(function(x, y) x * y, x, 2-(x %% 2))
# [1] 1 4 3 8 5
在这里,我们使用2-(1:5 %% 2)
获得1的赔率和2的赔率。