Home > OS >  Print names and nrow of a list of dataframes in a loop in R
Print names and nrow of a list of dataframes in a loop in R

Time:01-05

I loop with a list of dataframes and like to show their names and number of rows:

library(tidyverse)

data(Affairs, BankWages)
df_list <- list(Affairs, BankWages)
names(df_list) <- c("Affairs", "BankWages")
names(df_list[1]) # one works

for (i in df_list){
  #print(names(df_list[i])) # loop does not work 
  print(i %>% nrow())
}

Such that it repeats

Dataframe Affairs contains 601 observations
Dataframe BankWages contains 474 observations 

CodePudding user response:

Since you are loading tidyverse, you can use lst to create a named list, and map2_vec glue to create the sentences:

lst(mtcars, cars) %>% 
  map2_vec(names(.), ~ glue::glue("Dataframe {.y} contains {nrow(.x)} observations"))

output

Dataframe mtcars contains 32 observations
Dataframe cars contains 50 observations

Note that you need purrr 1.0.0 for map2_vec.

  • Related