Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple descriptive tables (with a loop) and storing as dataframes in R

I am trying to create a simple 'for loop' to produce a series of descriptive tables (saved as dataframes) using R but am struggling to do so.

For example, I can create a simple descriptive table (called 'Var_1_tab') like so:

library(janitor)

Var_1<- c("a", "b", "b", "a", "b", "b", "b")
Var_2<- c("b", "b", "a", "a", "a", "b", "a")
Var_3<- c("c", "b", "a", "c", "c", "b", "a")

df<- data.frame(Var_1, Var_2, Var_3)

Var_1_tab<- df %>% janitor::tabyl(Var_1)

I want to use a loop to sequence along each column in my dataframe and produce the same simple descriptive table for each column, storing the result in my global environment as a dataframe. Added bonus would be to be able to name each dataframe as 'Var_1_tab', 'Var_2_tab' etc, for ease of reference.

Can anyone help?

Thanks!!!

like image 727
C. Nugent Avatar asked Mar 14 '26 16:03

C. Nugent


1 Answers

tabyl can take quoted column names as well. So, we loop over the column names and save the output in a list

library(purrr)
library(dplyr)
df_lst <- map(names(df), ~ df %>% 
      janitor::tabyl(all_of(.x)))
names(df_lst) <- paste0(names(df), "_tab")

-output

> df_lst
$Var_1_tab
 Var_1 n   percent
     a 2 0.2857143
     b 5 0.7142857

$Var_2_tab
 Var_2 n   percent
     a 4 0.5714286
     b 3 0.4285714

$Var_3_tab
 Var_3 n   percent
     a 2 0.2857143
     b 2 0.2857143
     c 3 0.4285714

The list elements can be extracted with $ or [[ using the names

> df_lst[["Var_1_tab"]]
 Var_1 n   percent
     a 2 0.2857143
     b 5 0.7142857

If we need to create objects in the global env (not recommended), use list2env on the named list

list2env(df_lst, .GlobalEnv)

and check for the objects

> Var_1_tab
 Var_1 n   percent
     a 2 0.2857143
     b 5 0.7142857
> Var_2_tab
 Var_2 n   percent
     a 4 0.5714286
     b 3 0.4285714
like image 83
akrun Avatar answered Mar 16 '26 10:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!