7

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

Muhammad Kamil
  • 523
  • 1
  • 7

7 Answers7

7

Using lengths():

sum(lengths(mylist)) # 5

From the official documentation:

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

sindri_baldur
  • 25,109
  • 3
  • 30
  • 57
3
library(purrr)
mylist |> map(length) |> simplify() |> sum()
danlooo
  • 8,933
  • 1
  • 6
  • 21
3

You can try

lapply(mylist,length) |> unlist() |> sum()
denis
  • 5,142
  • 1
  • 10
  • 36
2

How about this:

sum(sapply(mylist, length))
DaveArmstrong
  • 11,680
  • 1
  • 10
  • 21
1

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
Maël
  • 15,428
  • 3
  • 14
  • 43
1

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

1

Another possible solution:

library(tidyverse)

mylist %>% flatten %>% length

#> [1] 5
PaulS
  • 10,636
  • 1
  • 7
  • 20