Getting nested elements from a list

99封情书 提交于 2019-12-11 03:36:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!