rdataframefor-loopautomationlm

How to create output dataframe name as per the input dataframe name in R?


I was trying to do regression modeling on multiple dataframes.

My expected outcome would name as per the input dataframe name, so I wonder how can I achieve that!

Till now what I did,

list.dfs <- list(BrC15sy_h16_d_EE86228,BrC15sy_h16_d_EE86235,BrC15sy_h16_d_EE86256,
                 BrC15sy_h16_d_EE86257,BrC15sy_h16_d_EE86267,BrC15sy_h16_d_EE86269)


for (i in 1:length(list.dfs)){

 lm.res <- lm(
    as.formula(paste(colnames(list.dfs[[i]])[1], "~ .")),
    data=list.dfs[[i]]
  )

  assign(paste0("lm_Res",i), lm.res, envir = .GlobalEnv)
}

This delivered the output dataframe as,

lm_Res1
lm_Res2
lm_Res3
lm_Res4
lm_Res5
lm_Res6

My expected output dataframe name should be,

lm_Res_BrC15sy_h16_d_EE86228
lm_Res_BrC15sy_h16_d_EE86235
lm_Res_BrC15sy_h16_d_EE86256
lm_Res_BrC15sy_h16_d_EE86257
lm_Res_BrC15sy_h16_d_EE86267
lm_Res_BrC15sy_h16_d_EE86269

Solution

  • First of all create list.dfs with named arguments, therefore, use

    list.dfs <- list(BrC15sy_h16_d_EE86228 = BrC15sy_h16_d_EE86228, ...)
    

    or more convenient, use the lst() function from the tibble library:

    list.dfs <- tibble::lst(BrC15sy_h16_d_EE86228, ...)
    

    Finally, replace paste0("lm_Res",i) inside the assign call with

    paste0("lm_Res_", names(list.dfs)[i])