Rana Mallah
Rana Mallah

Reputation: 167

How can I select multiple elements from the nth vector in a list?

I am trying to take in a character vector, do some operations on it, and then extract only the elements that match certain criteria.

c("a", "b", "b") %>% list(., which(.=="b")) %>% {.[[1]][[.[[2]]]]}

the list is made out of the character vector as the first element and an index vector - of the elements I want to extract - as the second element. But, when I try to use list subsetting in the final step, I get the error

Error in .[[1]][[.[[2]]]] : attempt to select more than one element in vectorIndex

How can I get the desired output:

c("b", "b")

Upvotes: 0

Views: 118

Answers (1)

mt1022
mt1022

Reputation: 17299

c("a", "b", "b") %>% list(., which(.=="b")) %>% {.[[1]][ .[[2]] ]}
# [1] "b" "b"

However, I would prefer

> x <- c('a', 'b', 'b')
> x[which(x == 'b')]
[1] "b" "b"

Doing everything by chaining looks fancy but may sacrifice readability and simplicity.

Upvotes: 2

Related Questions