Snoop Dogg
Snoop Dogg

Reputation: 391

Applying a function to a list of indexes of a vector?

I have a vector X of length n, and a list of indices L of variable length. Let F be a function from R^m to R. I want to apply the function F to each subvector X[L[[i]]. This is, I want to calculate F( X[ L[[i]] ] )

For example, suppose that F is the mean

set.seed(123)
X <- rnorm(100)
L <- list()
for(i in 1:10) L[[i]] <- sample(1:100,30,replace = FALSE)

By brute force I could calculate

out <- vector()
for(i in 1:10) out[i] <- mean(X[ L[[i]] ])

However, this for loop is rather slow for larger dimensions. I was wondering if there is a more direct way for calculating out? I have tried to use lapply but it does no seem to work for the combination of a vector + a list of indices + a function.

Upvotes: 0

Views: 342

Answers (1)

Sotos
Sotos

Reputation: 51602

You can simply use lapply to loop over your list and use each element to subset your vector X. Once you subset, calculate the mean, i.e.

lapply(L, function(i) mean(X[i]))

Upvotes: 2

Related Questions