Reputation: 71
I have a three dataframes with 77 variables. They are all the same, they only differ in years (2014, 2015, 2016).
I want to merge them, but all the colnames are exactly the same, So I don't know which values belong to 2014, 2015 or 2015.
I want to solve this by adding the year to all colnames in the three dataframes.
So now I have:
df_2014:
a|b|c
1|2|3
df_2015
a|b|c|
4|5|6|
df_2016
a|b|c|
7|8|9|
I would like to have:
df_2014:
a(2014)|b(2014)|c(2014)
1|2|3
df_2015:
a(2015)|b(2015)|c(2015)|
4|5|6|
df_2016:
a(2016)|b(2016)|c(2016)|
7|8|9|
Does anyone know if I can do this with a loop or another function? Otherwise I need to rename the colnames 231 times ;)
thanks, Arnand
Upvotes: 1
Views: 52
Reputation: 3514
You could use setNames. For instance:
df_2017 <- data.frame(a = 1, b = 2, c = 3)
setNames(df_2017, paste("df_2017",colnames(df_2017), sep = ""))
Output:
df_2017a df_2017b df_2017c
1 1 2 3
Upvotes: 1
Reputation: 8413
have them all in a list first:
l = list(df2014, df2015, df2016)
lapply(seq_along(l), function(x) {colnames(l[[x]]) = paste0(colnames(l[[x]]) ,"(", x+2013, ")");l[[x]]})
Upvotes: 1