0

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?

2
  • Though I am not clear on your query, but I think you require setNames Commented Feb 19, 2021 at 12:06
  • Thanks for the quick reply. Can you give an example how that should work? Commented Feb 19, 2021 at 12:11

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

5 Comments

Thanks this basically works in the created list. But when I try to retrieve the data frames from the list by list2env(list_4_river_df,envir = .GlobalEnv) I receive the following error: names(x) must be a character vector of the same length as x.
Just update the answer to include the list2env usecase
Well the command list2env does not create an error message anymore, but when I look at the single data frames afterwards they still have the old column names. :(
Hi there the code I share with you just show the result - you need to put them together to make it work. - I adjust the answers though
great, now it did the job perfectly. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.