问题
I am trying to get nested elements from a list. I can extract the elements using: unlist(pull_lists[[i]]$content[[n]]['sha'])
, however, it seems that I cannot insert them in a nested list. I have extracted a single element of the list in a gist, which creates the reproducible example below. Here is what I have so far:
library("devtools")
pull_lists <- list(source_gist("669dfeccad88cd4348f7"))
sha_list <- list()
for (i in length(pull_lists)){
for (n in length(pull_lists[[i]]$content)){
sha_list[i][n] <- unlist(pull_lists[[i]]$content[[n]]['sha'])
}
}
How can I insert the elements in a nested fashion?
回答1:
When I download the content, I get a much more complicated structure than you do. For me, it's not pull_lists[[i]]$content
, it's pull_lists[[i]]$value$content[[1 or 2]]$parents$sha
. The reason nothing is populating is because there is nothing there to populate (ie, n = 0).
I've had to deal with similar data structures before. What I found was that it's much easier to search the naming structure after unlisting rather than to figure out the correct sequence of subsets.
Here's an example:
sha_locations <- grep("sha$",names(unlist(pull_list[[1]])))
unlist(pull_list[[1]])[sha_locations]
Cleaning the for loop a bit, this would look like:
sha_list <- lapply(
pull_list,
function(x) unlist(x)[grep("sha$",names(unlist(x)))]
)
Since there are multiple SHAs, and the question only asks for the SHAs at specific positions, you need to extract those SHAs:
sha_list <- sha_list[[1]][attr(sha_list[[1]], "names")=="value.content.sha"]
来源:https://stackoverflow.com/questions/31613880/getting-nested-elements-from-a-list