Вот мой способ, который предполагает некоторую ручную работу.Предположим, ваш набор данных находится в переменной 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])
Редактировать:
Я обобщил решение, чтобы оно автоматически находило все дублированные столбцы и привязку строк к каждому
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)
Это сложно, когда вы пытаетесь связать столбцы, потому что объединенные данные могут иметь другой номер строки.Вы можете сравнивать длину каждый раз при объединении и заполнять более короткий список, добавляя 0 с.