Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth element of each item of a list, which is itself a vector of unknown length

If we have a list, and each item can have different length. For example:

l <- list(c(1, 2), c(3, 4,5), c(5), c(6,7))

(In order to be clear, we will call objects in a list "items", and objects in the objects of list "elements".)

How can we extract, for example the first element of each item? Here, I want to extract:

1, 3, 5, 6

Then same question for the second element of each item:

2, 4, NA, 7
like image 831
John Smith Avatar asked Mar 25 '17 09:03

John Smith


People also ask

How do you find the nth element in a list?

Use list indexing to get the nth element of a list. Use list indexing syntax list[index] with n - 1 as index , where n represents a value's placement in the list, to retrieve the respective nth element of a list.

How do you get the first element of a list in R?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).


2 Answers

We can create a function using sapply

fun1 <- function(lst, n){
         sapply(lst, `[`, n)
   }
fun1(l, 1)
#[1] 1 3 5 6

fun1(l, 2)
#[1]  2  4 NA  7
like image 148
akrun Avatar answered Oct 02 '22 16:10

akrun


data.table::transpose(l) will give you a list with vectors of all 1st elements, all 2nd elements, etc.

l <- list(1:2, 3:4, 5:7, 8:10)
b <- data.table::transpose(l)
b
# [[1]]
# [1] 1 3 5 8
# 
# [[2]]
# [1] 2 4 6 9
# 
# [[3]]
# [1] NA NA  7 10

If you don't want the NAs you can do lapply(b, function(x) x[!is.na(x)])

like image 28
IceCreamToucan Avatar answered Oct 02 '22 14:10

IceCreamToucan