简体   繁体   中英

Summing the lengths of lists inside a list in R

I have 2 lists inside a list in R. Each sublist contains a different number of dataframes. The data looks like this:

df1 <- data.frame(x = 1:5, y = letters[1:5])
df2 <- data.frame(x = 1:15, y = letters[1:15])
df3 <- data.frame(x = 1:25, y = letters[1:25])
df4 <- data.frame(x = 1:6, y = letters[1:6])
df5 <- data.frame(x = 1:8, y = letters[1:8])

l1 <- list(df1, df2)
l2 <- list(df3, df4, df5)
mylist <- list(l1, l2)

I want to count the total number of dataframes I have in mylist (answer should be 5, as I have 5 data frames in total).

Using lengths() :

sum(lengths(mylist)) # 5

From the official documentation:

[...] a more efficient version of sapply(x, length)

library(purrr)
mylist |> map(length) |> simplify() |> sum()

You can try

lapply(mylist,length) |> unlist() |> sum()

How about this:

sum(sapply(mylist, length))

You can unlist and use length .

length(unlist(mylist, recursive = F))
# [1] 5

Forr lists of arbitrary length, one can use rrapply::rrapply :

length(rrapply(mylist, classes = "data.frame", how = "flatten"))
# 5

length(unlist(mylist, recursive = F)) should work.

Another possible solution:

library(tidyverse)

mylist %>% flatten %>% length

#> [1] 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM