Reputation: 594
Is there a way to select multiple elements of multiple vectors stored in a list? The position of each element I am interested in selecting for each vector is the same. Consider the following MWE of a list with a length of 3. Each vector within the list is of equal length too.
# create list and vectors within storing random data
mylist<- list(rnorm(5), rgeom(5, 0.05), rbinom(5, 10, 0.5))
If I want to select the 1st and 3rd element of the 1st vector I write mylist[[1]][c(1,3)]
and this returns the values of elements in position 1 and 3. Similarly, for the second vector, I write mylist[[2]][c(1,3)]
.
But how can I write some neat code so that I can select the 1st and 3rd element of both the 1st and 2nd vectors in the list at the same time? I have tried mylist[c(1, 2)][c(1, 3)]
but this returns all the elements of the 1st vector and NULL
for the second vector.
EDIT
Once the elements have been selected how does one overwrite them, such that (for example) mylist[c(1, 2)][c(1,3)] <- 0
Upvotes: 5
Views: 1347
Reputation: 887153
We can use map_at
library(purrr)
map_at(mylist, 1:2, ~ replace(.x, c(1, 3), 0))
#[[1]]
#[1] 0.00000000 -0.23017749 0.00000000 0.07050839 0.12928774
#[[2]]
#[1] 0 61 0 8 8
#[[3]]
#[1] 4 3 8 7 6
set.seed(123)
mylist<- list(rnorm(5), rgeom(5, 0.05), rbinom(5, 10, 0.5)
Upvotes: 1
Reputation: 388982
We could use lapply
lapply(mylist[1:2], `[`, c(1, 3))
#[[1]]
#[1] -0.5604756 1.5587083
#[[2]]
#[1] 6 55
which is similar to map
in purrr
purrr::map(mylist[1:2], `[`, c(1, 3))
To update the values of selected elements, we can do
mylist[1:2] <-lapply(mylist[1:2], function(x) {x[c(1, 3)] <- 0;x})
mylist
#[[1]]
#[1] 0.00000000 -0.23017749 0.00000000 0.07050839 0.12928774
#[[2]]
#[1] 0 61 0 8 8
#[[3]]
#[1] 4 3 8 7 6
data
set.seed(123)
mylist<- list(rnorm(5), rgeom(5, 0.05), rbinom(5, 10, 0.5))
Upvotes: 7