# load packages
library(tidyverse)
# define function to allow cbinding DFs of different length
# taken from: https://stackoverflow.com/a/7962286
cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
# make some sample DFs
df1 <- data.frame(a = 1:3, b = 4:6)
df2 <- data.frame(a = 1:5, b = 6:10)
# merge them and reorder collate col positions
cbind.fill(df1, df2) %>%
as_tibble(.name_repair = "unique") %>%
select(c(seq(1, ncol(.), 2), seq(2, ncol(.), 2)))
#> New names:
#> * a -> a...1
#> * b -> b...2
#> * a -> a...3
#> * b -> b...4
#> # A tibble: 5 x 4
#> a...1 a...3 b...2 b...4
#> <int> <int> <int> <int>
#> 1 1 1 4 6
#> 2 2 2 5 7
#> 3 3 3 6 8
#> 4 NA 4 NA 9
#> 5 NA 5 NA 10
由reprex package (v1.0.0) 于 2021-03-25 创建