Dominix
Dominix

Reputation: 441

Subset list by varying index

I am trying to subset values from a list object based on a varying index.

I have tried the standard sub-setting strategies, like lapply. However, they only work for a fixed index. E.g., sub-setting the first value of every list element. Yet, I want to select a different index position in every list element.

Consider the following list:

mylist<-list(c("25","0","33"),c("50","1"),c("100","2","3", "45"),c("12", "54"))

I can easily subset for the first value in each list element using lapply:

lapply(mylist,"[", 1)

This gives me the first value in each list element. However, consider a situation in which I want the second value at the first element, the first value at the second element, the third value at the third element, etc. Put differently, I would like to subset by a varying index, e.g.,:

var.index <- c(2,1,3,1)

So I receive the final values

c(0,50,3,12)

Any ideas? Thanks for any help.

Upvotes: 4

Views: 398

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

Since mylist and var.index would have same length you could also use sapply/lapply

sapply(seq_along(mylist), function(x) mylist[[x]][var.index[x]])
#[1] "0"  "50" "3"  "12"

Upvotes: 2

jay.sf
jay.sf

Reputation: 72828

You could use mapply with which you may loop through multiple ordered sets in the order of their elements.

mapply(function(x, y) x[y], mylist, var.index)
# [1] "0"  "50" "3"  "12"

Upvotes: 4

Related Questions