0

Is there a best way to extract the lower elements of a list?
For example this list people has a series of "peoples", each with a number "R" attached as people[[i]]$Expertise$R.
Is there a best way to extract them as a vector?
I hoped to use rlist and its good for loads of things I needed but I can't see a function for this.
Here is an example doing what I need but maybe suboptimally:

#https://renkun.me/rlist-tutorial/Features/Filtering.html
#install.packages("rlist")

library(rlist)
people <- list.load("http://renkun.me/rlist-tutorial/data/sample.json")
length(people)
str(people)
people[[1]][[1]]$R
str(list.filter(people, Age >= 25))

Rskill<-numeric()
for(i in 1:length(people)) 
Rskill<-c(Rskill,people[[i]]$Expertise$R)
Rskill

unlist(lapply(1:length(people),function(i) people[[i]]$Expertise$R))
Aurèle
  • 12,545
  • 1
  • 31
  • 49
user3156942
  • 163
  • 1
  • 8
  • Please provide a reproducible example. http://stackoverflow.com/q/5963269/1691723 – Sathish Mar 19 '17 at 08:43
  • @Sathish: OP's example appears reproducible to me – Aurèle Mar 19 '17 at 08:57
  • I'm not familiar with `rlist`, but you can make your `lapply()` a bit simpler and more robust with: `vapply(people, function(p) p$Expertise$R, integer(1))` – Aurèle Mar 19 '17 at 09:02
  • thanks, a p o m, vapply looks useful - the main difference to lapply seems to be you can specify whats returned ? – user3156942 Mar 19 '17 at 10:20
  • @apom it would be better, if OP provided data using `dput` and the desired output, otherwise people will tend to assume a lot and guess work will come in. – Sathish Mar 19 '17 at 10:50

3 Answers3

0

I think sapply is the simplest way to extract R values as a vector:

sapply(people,function(l)l$Expertise$R)
Feng
  • 603
  • 3
  • 9
0

I don't know the rlist package, but you may extract the Rskill via

sapply(people, function(x) x$Expertise$R)

or, if you prefer a loop, with

Rskill <- numeric(length(people))
for (i in seq_along(people))
    Rskill[[i]] <- people[[c(i, 4, 1)]]

The latter works because lists are 'vectors' in the sense that you can meaningfully address (e.g., extract) the n-th element. In a nested list, you can access a single element by a numeric vector.

Enrico Schumann
  • 1,278
  • 7
  • 8
0

vapply() is a more robust alternative to your lapply(), ensuring the type of the output (here, "integer"):

vapply(people, function(p) p$Expertise$R, integer(1))
# [1] 2 3 1

rlist appears to provide similar functionality with list.mapv():

list.mapv(people, .$Expertise$R, "integer")
# [1] 2 3 1

# Or even simpler, saving typing two characters ;-)
list.mapv(people, Expertise$R, "integer")
# [1] 2 3 1
Aurèle
  • 12,545
  • 1
  • 31
  • 49