Sojers Sojers - 1 year ago 66
R Question

How do i use apply with an array and a scalar?

If I have an array

a = c(1,2,3,1,2,3,1,2,3,1,2,3)

I would like to apply the "which" function to each scalar in 1:3

l = list()
for(i in 1:3){
l[[i]] = which(a == i)

how do I vectorize this operation with a apply, lapply, Map?

Answer Source

The main argument of lapply should be the dimension of list elements you want to end up with. Which is the what you are looping over in your for example, so:

a = c(1,2,3,1,2,3,1,2,3,1,2,3)
lapply(1:3, function(x) which(a == x))

Alternatively, if you don't want to code a into the anonymous function you can use:

lapply(1:3, function(x, y) which(y == x), y = a)