Home > Net >  A for() loop to overwrite existing data.frames
A for() loop to overwrite existing data.frames

Time:10-15

I'm testing some operations with that classical 99' Czech Bank data set, trying to execute a tidyverse task upon several data.frames in my global environment, but the loop I've created keeps overwriting the same object val, which was supposed to be a dummy for the df themselves:

x <- c("loans93","loans94","loans95","loans96",
       "loans97","loans98")
x <- base::mget(x, envir=as.environment(-1), mode= "any", inherits=F)

for (val in x) {
  val <- val %>%
    select(account_id, district_id, balance, status, date) %>% 
    group_by(account_id, district_id, status, date) %>%
    summarise(balance=mean(balance, na.rm=T)) %>%
    ungroup()
}

What am I doing wrong? I've searched for similar questions but people keep answering lapply solutions and what not... I just need the task to be saved upon my DFs instead of this "val" object I keep getting... Help!

CodePudding user response:

you could try this:

df_names <- c("loans93", "loans94", "loans95",
              "loans96", "loans97", "loans98")

for(df_name in df_names){
    get(df_name) %>%
        head %>% ## replace with desired manipulations
        assign(value = .,
               x = paste0(df_name,'_manipulated'), ## or just: df_name to overwrite original
               envir = globalenv())
}

aside: list2env is handy to "spawn" list members (e. g. dataframes) into the environment. Example:

list_of_dataframes <- list(
    iris_short = head(iris),
    cars_short = head(cars)
)

list2env(x = list_of_dataframes)
  • Related