简体   繁体   中英

Iterating through subelements of a list

I have a list that I want to iterate through:

library(RCurl)
data <- getURL("https://gist.githubusercontent.com/aronlindberg/b6b934b39e3c3378c3b2/raw/9b1efe9340c5b1c8acfdc90741260d1d554b2af0/data")
pull <- dget(textConnection(data))

I can access an individual element like this:

pull$content[[1]]$filename

But I want to access all the elements (eg [[2]]@filename , [[3]]$filename , etc.). I think this should do it:

n <- list(1:length(pull$content))
output <- list(1:length(n))
for (i in n){
  output[[i]] <- pull$content[[i]]$filename
}

However, it returns Error in pull$content[[n]] : recursive indexing failed at level 3 .

What am I doing wrong? How can I return the list properly?

The more idiomatic way of extracting all the filename values would be

sapply(pull$content, "[[", "filename")

This is because in most cases

obj$prop
obj[["prop"]]

return the same thing, but the latter form allows you to pass character values for the value you want to extract where as it's harder to dynamically extract different values with the $ syntax. So basically we're calling the [[ extract function on each of the content values and are requesting the filename value.

But your specific error message is generated because you have placed your indexes in a list

n <- list(1:length(pull$content))
length(n)
# [1] 1

Note that this a list of length 1 that contains the vector 1:30. This means your loop will only iterate once, and when it does, i will be 1:30 . That means that it will try to do

pull$content[[1:30]]$filename

which throws the recursive indexing error. This is because when you pass a vector to [[ , rather than extracting multiple lists, it descents a lists of lists looking for particular indexes. For example

a <- list(list(9,list(list(7,6,list(4)), 8), 10))
a[[1]][[2]][[1]][[3]][[1]]
# [1] 4
a[[c(1,2,1,3,1)]]
# [1] 4

So it takes the first index of a , then the second index of the resulting list, then the first index of the resulting list, etc. That's where the "recursive" part is coming form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM