How to extract values ​​from a single list in R?

For example, how to get a vector of each age in the people list below:

 > people = vector("list", 5) > people[[1]] = c(name="Paul", age=23) > people[[2]] = c(name="Peter", age=35) > people[[3]] = c(name="Sam", age=20) > people[[4]] = c(name="Lyle", age=31) > people[[5]] = c(name="Fred", age=26) > ages = ??? > ages [1] 23 35 20 31 26 

Is there an equivalent to understanding a Python list or something like that?

+8
list r extract
source share
4 answers

You can use sapply :

 > sapply(people, function(x){as.numeric(x[2])}) [1] 23 35 20 31 26 
+15
source share

Given the data structure you provided, I would use sapply :

 sapply(people, function(x) x[2]) > sapply(people, function(x) x[2]) age age age age age "23" "35" "20" "31" "26" 

However, you will notice that the results of this are character data.

 > class(people[[1]]) [1] "character" 

One approach would be to force as.numeric() or as.integer() in a sapply call.

Alternatively, if you have the flexibility regarding how you store data in the first place, it might make sense to save it as a list of data.frame s:

 people = vector("list", 5) people[[1]] = data.frame(name="Paul", age=23) people[[2]] = data.frame(name="Peter", age=35) ... 

If you are going to go this far, you can also consider one data file for all of your data:

 people2 <- data.frame(name = c("Paul", "Peter", "Sam", "Lyle", "Fred") , age = c(23,35,20,31, 26)) 

Perhaps there is another reason why you did not consider this approach for the first time, though ...

+6
source share
 ages <- sapply(1:length(people), function(i) as.numeric(people[[i]][[2]])) ages 

Output:

[1] 23 35 20 31 26

+1
source share

As an alternative to the apply family, there is @Hadley purrr package , which offers map_ functions for this kind of work.

(There are several differences from apply -family, for example, here .)

Example OPs:

 people = vector("list", 5) people[[1]] = c(name="Paul", age=23) people[[2]] = c(name="Peter", age=35) people[[3]] = c(name="Sam", age=20) people[[4]] = c(name="Lyle", age=31) people[[5]] = c(name="Fred", age=26) 

sapply approach:

 ages_sapply <- sapply(people, function(x){as.numeric(x[2])}) print(ages_sapply) [1] 23 35 20 31 26 

And map approach:

 ages_map <- purrr::map_dbl(people, function(x){as.numeric(x[2])}) print(ages_map) [1] 23 35 20 31 26 

Of course, they are the same:

 identical(ages_sapply, ages_map) [1] TRUE 
0
source share

All Articles