从列表中获取嵌套元素 [英] Getting nested elements from a list
问题描述
我正在尝试从列表中获取嵌套元素.我可以使用unlist(pull_lists[[i]]$content[[n]]['sha'])
提取元素,但是,似乎无法将它们插入嵌套列表中.我已根据要点提取了列表的单个元素,从而在下面创建了可重现的示例.这是我到目前为止的内容:
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?
推荐答案
下载内容时,我得到的结构要比您复杂得多.对我来说,它不是pull_lists[[i]]$content
,它是pull_lists[[i]]$value$content[[1 or 2]]$parents$sha
.没什么可填充的原因是因为那里没有可填充的东西(即n = 0).
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.
这是一个例子:
sha_locations <- grep("sha$",names(unlist(pull_list[[1]])))
unlist(pull_list[[1]])[sha_locations]
稍微清洁一下for循环,这看起来像:
Cleaning the for loop a bit, this would look like:
sha_list <- lapply(
pull_list,
function(x) unlist(x)[grep("sha$",names(unlist(x)))]
)
由于存在多个SHA,并且该问题仅要求在特定位置提供SHA,因此您需要提取这些SHA:
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"]
这篇关于从列表中获取嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!