查找R中列表列表的长度
我有一个列表,希望找到每个列表的长度。列表列表称为查找R中列表列表的长度,r,list,R,List,我有一个列表,希望找到每个列表的长度。列表列表称为GroupedList,每个列表包含两列 [[1]] preds ground_truth 21528 1 1 14033 1 0 3770 1 1 16734 1 1 20867 1 0 26342 1
GroupedList
,每个列表包含两列
[[1]]
preds ground_truth
21528 1 1
14033 1 0
3770 1 1
16734 1 1
20867 1 0
26342 1 1
687 1 1
7501 1 1
15543 1 1
13239 1 0
3403 1 1
[[2]]
preds ground_truth
5278 1 1
4745 1 1
12622 1 0
26877 1 1
441 1 1
20626 1 1
[[3]]
preds ground_truth
7431 1 1
16675 1 1
[[4]]
[1] preds ground_truth
<0 rows> (or 0-length row.names)
我需要输出能够检查和打印每个列表的长度分别。这样做的原因是能够在如下条件下使用列表的长度:
for (list in GroupedList){
if(length(list) > 0){
print(list)}
}
有人能告诉我如何计算单个列表中的元素吗。我建议使用这种方法。您可以使用
lappy()
,因为您有一个列表,并使用do.call()
和rbind()绑定结果:
更新:这里是另一种使用for()的方法。
简短版本:
sapply(GroupedList, nrow)
@geds133就不一样了,如果在获得维度后,你过滤掉那些零维度的话?我不明白我在你的答案中定义了什么。还有,有了这个答案,我还能保留列表编号吗?还有,这确实保留了列表名称并计算了变量,但是我不明白如何有条件地使用这个新输出来编辑原始列表。@geds133我添加了一个更新,请检查,最终输出是一个数据帧,然后您可以从中获取值以执行其他任务。计算机关机后将在备份时进行检查。或者Map(nrow,GroupedList)
尝试length(list[[1]])>0
或if
条件下的nrow(list)>0
。
#Data
List <- list(structure(list(preds = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), ground_truth = c(1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L,
1L, 0L, 1L)), class = "data.frame", row.names = c("21528", "14033",
"3770", "16734", "20867", "26342", "687", "7501", "15543", "13239",
"3403")), structure(list(preds = c(1L, 1L, 1L, 1L, 1L, 1L), ground_truth = c(1L,
1L, 0L, 1L, 1L, 1L)), class = "data.frame", row.names = c("5278",
"4745", "12622", "26877", "441", "20626")), structure(list(preds = c(1L,
1L), ground_truth = c(1L, 1L)), class = "data.frame", row.names = c("7431",
"16675")), structure(list(preds = integer(0), ground_truth = integer(0)), row.names = character(0), class = "data.frame"))
#Obtain dim
O <-as.data.frame(do.call(rbind,lapply(List,function(x) dim(x)[1])))
#Format
O$List <- rownames(O)
O <- O[,c(2,1)]
names(O)[2]<-'count'
rownames(O)<-NULL
List count
1 1 11
2 2 6
3 3 2
4 4 0
#Data
List2 <- list(l1 = list(structure(list(preds = c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), ground_truth = c(1L, 0L, 1L, 1L, 0L, 1L,
1L, 1L, 1L, 0L, 1L)), class = "data.frame", row.names = c("21528",
"14033", "3770", "16734", "20867", "26342", "687", "7501", "15543",
"13239", "3403"))), l2 = list(structure(list(preds = c(1L, 1L,
1L, 1L, 1L, 1L), ground_truth = c(1L, 1L, 0L, 1L, 1L, 1L)), class = "data.frame", row.names = c("5278",
"4745", "12622", "26877", "441", "20626"))), l3 = list(structure(list(
preds = c(1L, 1L), ground_truth = c(1L, 1L)), class = "data.frame", row.names = c("7431",
"16675"))), l4 = list(structure(list(preds = integer(0), ground_truth = integer(0)), row.names = character(0), class = "data.frame")))
#Create empty list to save results
elist <- list()
#Loop
for(i in 1:length(List2))
{
#Check dim
if(dim(List2[[i]][[1]])[1]>0)
{
df <- data.frame(name=names(List2[i]),count=dim(List2[[i]][[1]])[1])
elist[[i]] <- df
}
}
#Now bind
O <- do.call(rbind,elist)
name count
1 l1 11
2 l2 6
3 l3 2
sapply(GroupedList, nrow)