climsaver
climsaver

Reputation: 617

Change column names for multiple data frames in a loop

I have four data frames for four different river data sets (the rivers are Main, Danube, Isar and Inn). The data frames are all of the same dimensions and are named as follows: "df_Main", "df_Danube", "df_Isar" and "df_Inn". In order for handy plotting afterwards, I need all the data frames to have the same column names. I thought it can easily be achieved by this:

rivers <- c("Main", "Danube", "Isar", "Inn")
for (i in 1:length(rivers)) {
  colnames(get(paste0("df_", rivers[i]))) <- c("bla", "bla", "bla", "bla")
}

But that does not work. Anybody with an idea?

Upvotes: 0

Views: 773

Answers (2)

Sinh Nguyen
Sinh Nguyen

Reputation: 4487

A pseudo code

library(purrr) # using purrr for map function
# create a list of 4 data frame
# another alternatives is define the initial list with names
list_4_river_df <- list(df_Main = df_Main, df_Danube = df_Danube,
                        df_Isar = df_Isar, df_Inn = df_Inn)
# map setNames to each dataframe in the list
list_4_river_df <- map(list_4_river_df, setNames, nm = c("bla_1", "bla_2", "bla_3", "bla_4", "bla_5"))

# then list2env should work perfectly
list2env(list_4_river_df,envir = .GlobalEnv)

Upvotes: 1

Carles Borred&#225;
Carles Borred&#225;

Reputation: 358

If you want to go this way you probably need the function assign. As an example:

rivers <- c("df_Main", "df_Danube", "df_Isar", "df_Inn")

for (i in rivers) {
  x=get(i)
  colnames(x) <- c("bla", "bla", "bla", "bla")
  assign(i,x)
}

If you need to do it for more than 4 data.frames maybe you should check an apply function.

Still, if you plan to plot it via ggplot2 it might be more useful to have it in a single df.

Upvotes: 2

Related Questions