I have a list of data frames and I want to replace column names that start with "..." with the name of the column before.
So the starting point is as follows:
df1 <- data.frame(Tree=c(1:3), Sea=c(4:6), ...3=c(2:4), Beach=c(1:3), ...5=c(2:4))
df1
df2 <- data.frame(Tree=c(1:3), Sea=c(4:6), ...3=c(2:4), Beach=c(1:3), ...5=c(2:4))
df2
df3 <- data.frame(Tree=c(1:3), Sea=c(4:6), ...3=c(2:4), Beach=c(1:3), ...5=c(2:4))
df3
df.list<-list(df1, df2, df3)
And I want the columns in the data frames in the list look as follows:
df1 <- data.frame(Tree=c(1:3), Sea=c(4:6), Sea=c(2:4), Beach=c(1:3), Beach=c(2:4))
df1
df2 <- data.frame(Tree=c(1:3), Sea=c(4:6), Sea=c(2:4), Beach=c(1:3), Beach=c(2:4))
df2
df3 <- data.frame(Tree=c(1:3), Sea=c(4:6), Sea=c(2:4), Beach=c(1:3), Beach=c(2:4))
df3
The problem initially arose because I have imported several data frames from Excel in a list where the column names ranged over two columns. I could not manage to label both columns with the same column name when importing the data.
I would really appreciate your help. Thanks!
I would suggest next approach. You can use a function and
lapply()
in order to set the change you want. In the functionmyname()
is defined a structure to detect a pattern in the names and then set toNA
. After that, we will usezoo
functionna.locf()
in order to complete the names with previous values. Also, sometimesR
has issues with duplicated names in a dataframe, that is why I left as a comment a line that can avoid that and you should comment the line that is next of that comment if unique names were needed. Here the code:Output: