For example, how do I get a vector of each and every person's age in the list people
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 of a Python list comprehension or something to the same effect?
You can use sapply:
> sapply(people, function(x){as.numeric(x[2])})
[1] 23 35 20 31 26
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'll notice that the results of this are character data.
> class(people[[1]])
[1] "character"
One approach would be to coerce to as.numeric()
or as.integer()
in the call to sapply.
Alternatively - if you have flexibility over how you store the data in the first place, it may make sense to store 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 that far, you may also want to consider a single data.frame for all of your data:
people2 <- data.frame(name = c("Paul", "Peter", "Sam", "Lyle", "Fred")
, age = c(23,35,20,31, 26))
There may be some other reason why you didn't consider this approach the first time around though...
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