Here is my way that involves some manual work. Let's assume your dataset is in the variable test
# may only require some of the packages of tidyverse
library(tidyverse)
# this will give all column unique names
renamed_test <- test %>%
set_names(str_c(names(test), 1:ncol(test)))
# then for each duplicated column name, they now start with the same prefix;
# so select all these columns and use gather to append them one after another,
# and finally rename the merged column back to the original name
bound_col_1 <- renamed_test %>%
select(starts_with("Col_1")) %>%
gather %>%
transmute(Col_1 = value)
# repeat this for 'Col_2'
# .....
# last, column bind all these results
bind_cols(bound_col_1, bound_col_2, [potentiall other variables])
Edit:
I generalized the solution so it will automatically find all duplicated columns and row bind each
library(tidyverse)
# testing data
test <- data.frame(c(1,2,3), c(7,8,9), c(4,5,6), c(10,11,12), c(100, 101, 102)) %>%
set_names(c("Col_1", "Col_2", "Col_1", "Col_2", "Col_3"))
col_names <- names(test)
# find all columns that have duplicated columns
dup_names <- col_names[duplicated(col_names)]
# make the column names unique so it will work with tidyr
renamed_test <- test %>%
set_names(str_c(col_names, "-", 1:ncol(test)))
unique_data <- test[!(duplicated(col_names) | duplicated(col_names, fromLast = TRUE))]
# for each duplicated column name, merge all columns that have the same name
dup_names %>% map(function(col_name) {
renamed_test %>%
select(starts_with(col_name)) %>%
gather %>% # bind rows
select(-1) %>% # merged value is the last column
set_names(c(col_name)) # rename the column name back to its original name
}) %>% bind_cols
result <- bind_rows(tmp_result, unique_data)
This is tricky when you try to bind the columns because the merged data might have different row number. You can compare the length every time when merging and fill the shorter list by appending 0s.