Home > other >  Defining multiple dataframes with for loop from list object
Defining multiple dataframes with for loop from list object

Time:11-14

Very green R user here. Sorry if this is asked and answered somewhere else, I haven't been able to find anything myself.

I can't figure out why I can't get a for loop to work define multiple new dataframes but looping through a predefined list.

My list is defined from a subset of variable names from an existing dataframe:

varnames <- colnames(dplyr::select(df_response, -1:-4))

Then I want to loop through the list to create a new dataframe for each variable name on the list containing the results of summary function:

for (i in varnames){
     paste0("df_",i) <- summary(paste0("df$",i))
}

I've tried variations with and without paste function but I can't get anything to work.

CodePudding user response:

paste0 returns a string. Both <- and $ require names, but you can use assign and [[ instead. This should work:

varnames <- colnames(dplyr::select(df_response, -1:-4))

for (i in varnames){
  assign(
    paste0("df_", i),
    summary(df[[i]])
  )
}

Anyway, I'd suggest working with a list and accessing the summaries with $:

summaries <- df_response |> 
  dplyr::select(-(1:4)) |>
  purrr::imap(summary)

summaries$firstvarname
  • Related