I have a list of vectors (mylist
):
a <- c(1,2,3,4)
b <- c(5,6,7,8)
c <- c(9,10,11,12)
mylist <- list(a,b,c)
I also have a vector of positions (mypos
):
mypos <- c(1,2,3)
I would like to use mypos
to give the position of elements to subset each vector of mypos
so that it returns:
[1] 1 6 11
I have tried using lapply like this:
lapply(mylist, "[", mypos)
but this returns elements 1, 2 and 3 of each vector:
[[1]]
[1] 1 2 3
[[2]]
[1] 5 6 7
[[3]]
[1] 9 10 11
I have also tried:
lapply(mylist, subset, mypos)
But this returns an error that the subset must be logical
The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.
Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.
There are three subsetting operators, [[ , [ , and $ . Subsetting operators interact differently with different vector types (e.g., atomic vectors, lists, factors, matrices, and data frames). Subsetting can be combined with assignment.
Subsetting matrices A matrix is subset with two arguments within single brackets, [] , and separated by a comma. The first argument specifies the rows, and the second the columns.
We can use Map
to extract the corresponding elements of 'mylist' from the index of 'mypos'
Map(`[`, mylist, mypos)
In the OP's code, the 'mypos' is repeated in each of list
elements resulting in extracting all the elements from the index. Instead it could be looped on sequence
lapply(seq_along(mylist), function(x) mylist[[x]][mypos[[x]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With