Home > database >  Summing the lengths of lists inside a list in R
Summing the lengths of lists inside a list in R

Time:04-22

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).

CodePudding user response:

Using lengths():

sum(lengths(mylist)) # 5

From the official documentation:

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

CodePudding user response:

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

CodePudding user response:

You can try

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

CodePudding user response:

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

CodePudding user response:

How about this:

sum(sapply(mylist, length))

CodePudding user response:

Another possible solution:

library(tidyverse)

mylist %>% flatten %>% length

#> [1] 5

CodePudding user response:

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
  • Related