Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset list of vectors with vector of positions

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

like image 240
John L. Godlee Avatar asked Feb 21 '17 17:02

John L. Godlee


People also ask

How do you subset vectors?

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.

How do I extract elements from a vector in R?

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.

What are the three subsetting operators in R?

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.

How do you subset a matrix?

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.


1 Answers

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]]])
like image 55
akrun Avatar answered Sep 27 '22 21:09

akrun