如何通过R中的多个子列表运行函数?

问题描述

我有一个名为AllVotes的复杂嵌套列表,您可以在这里找到(在.rds中):

https://github.com/JMcrocs/MEPVote/blob/master/FinalVotes.rds

我正在尝试收集所有mepid,这是一个存储在子列表AllVotes[[x]]$Votes$'+'$groups中的命名数字。感谢这里的上一个问题,我可以为一个列表([[1]]列表)执行此操作,但是我想对我的嵌套列表中从[[1]]到[[2336])的所有列表执行此操作]。

#For the list [[1]]
Result = c(unlist( sapply ( names ( AllVotes[[1]]$Votes$'+'$groups ),function(x) unlist( AllVotes[[1]]$Votes$'+'$groups[[x]] ) ) ),unlist( sapply ( names ( AllVotes[[1]]$Votes$'-'$groups ),function(x) unlist( AllVotes[[1]]$Votes$'-'$groups[[x]] ) )),unlist( sapply ( names ( AllVotes[[1]]$Votes$'0'$groups ),function(x) unlist( AllVotes[[1]]$Votes$'0'$groups[[x]] ) )))

我该怎么做?预先谢谢你!

PS:很抱歉,如果这个问题还不够完善,我是编程(和溢出)的两周新手。

解决方法

您可以尝试使用循环并将结果保存在下一个列表中:

#Load
AllVotes <- readRDS('FinalVotes.rds')
#Loop
#Empty list
List <- list()
#For
for(i in 1:length(AllVotes))
{
  List[[i]] <- c(unlist( sapply ( names ( AllVotes[[i]]$votes$'+'$groups ),function(x) unlist( AllVotes[[i]]$votes$'+'$groups[[x]] ) ) ),unlist( sapply ( names ( AllVotes[[i]]$votes$'-'$groups ),function(x) unlist( AllVotes[[i]]$votes$'-'$groups[[x]] ) )),unlist( sapply ( names ( AllVotes[[i]]$votes$'0'$groups ),function(x) unlist( AllVotes[[i]]$votes$'0'$groups[[x]] ) )))
}

您将最终获得List个元素,其中2336个元素。您可以使用例如List[[15]]等来访问元素。然后,您可以根据需要处理列表。

,

这是使用export const Field = ({fieldType,}) => { const input = () => { return <input /> } return ( <> <label htmlFor={name}> {label}</label> {input()} </> ); }; 的策略。将您的代码转换为匿名函数,将lapply()替换为函数的参数,例如AllVotes[[1]]

list

我使用AllVotes <- readRDS('FinalVotes.rds') out_list <- lapply(AllVotes,function(list) { c(unlist(sapply(names(list$votes$'+'$groups),function(x) unlist(list$votes$'+'$groups[[x]]))),unlist(sapply(names(list$votes$'-'$groups),function(x) unlist(list$votes$'-'$groups[[x]]))),unlist(sapply(names(list$votes$'0'$groups),function(x) unlist( list$votes$'0'$groups[[x]])))) }) 程序包对Duck的for循环答案进行了基准测试,以使每个版本运行100次。 rbenchmark的两个参数是我定义为两种方法的包装器的函数,因此输出将更易于解释。

benchmark()

看来这两种方法在我的机器上几乎相同,每次迭代大约需要1秒。循环版本的速度要快一点,但是差异很小,以至于不同的机器可能会更快地运行lapply版本。对于非常大的文件,其中之一可能会成为明显的赢家。另外,如果文件很大,则很容易并行处理lapply版本。

,

您可以将代码简化为:

res <- lapply(AllVotes,function(x){
  unlist(lapply(c('+','-','0'),function(y){
    x$votes[[y]]$groups
  }))
})

@Duck 的答案输出相同。

all.equal(res,List,check.attributes = F)
# [1] TRUE