Home > Back-end >  Is it possible to create a loop in R that changes the name of some variables in a list of dataframes
Is it possible to create a loop in R that changes the name of some variables in a list of dataframes

Time:04-01

I'm trying to create a loop that renames some variables in a list of data frames and sorts the rows using a variable. I have tried with this code (_var1, _var2 and var3 are present in each dataframe):

dfnames <- c("df1", "df2", "df3", "df4", "df5", "df5", "df6")

for (cur.dfname in dfnames) {   
  cur.df <- get(cur.dfname)
  cur.df <- rename(cur.df, var1 = "_var1", var2 = "_var2")
  cur.df <- arrange(cur.df, var3, desc(var1))
}

This code does not appear to work and no error message is generated.

CodePudding user response:

The object cur.df is only known inside the (scope of the) loop. To change the dataframe(s) outside the loop, you can assign it to the parent environment like:

for (cur.dfname in dfnames) {   
  cur.df <- get(cur.dfname)
  cur.df <- rename(cur.df, 'var1' = '_var1')
  cur.df <- arrange(cur.df, 'var1')
  ## manipulate objects beyond the loop scope:
  assign(cur.dfname, cur.df, envir = parent.frame(1))
}

Note that such scope breaking is considered bad practice.

  • Related