Reputation: 8806
The following lapply
multiply each element in the list by 2
lapply(1:5, function(x, y) x * y, y = 2)
Is it possible to use lapply
to specify a different y
for each element in the list? The following pseudo code is an example:
lapply(1:5, function(x, y) x * y, y = 1 if x is odd and = 2 if x is even)
Upvotes: 1
Views: 120
Reputation: 206242
sapply
and lapply
only allow for one varying argument. If you have multiple you can use mapply
or Map
. For example
x<-1:5
mapply(function(x, y) x * y, x, 2-(x %% 2))
# [1] 1 4 3 8 5
Here we use 2-(1:5 %% 2)
to get a 1 for odds and 2 for evens.
Upvotes: 2