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
  • 635
  • 2
  • 15

7 Answers7

7

Using lengths():

sum(lengths(mylist)) # 5

From the official documentation:

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

s_baldur
  • 29,441
  • 4
  • 36
  • 69
3
library(purrr)
mylist |> map(length) |> simplify() |> sum()
danlooo
  • 10,067
  • 2
  • 8
  • 22
3

You can try

lapply(mylist,length) |> unlist() |> sum()
denis
  • 5,580
  • 1
  • 13
  • 40
2

How about this:

sum(sapply(mylist, length))
DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
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
  • 45,206
  • 3
  • 29
  • 67
1

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

goblinshark
  • 133
  • 9
1

Another possible solution:

library(tidyverse)

mylist %>% flatten %>% length

#> [1] 5
PaulS
  • 21,159
  • 2
  • 9
  • 26