简体   繁体   中英

Print names and nrow of a list of dataframes in a loop in R

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 

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 .

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