如何在 R 中绑定不同列数的数据?

How to rbind the data with different number of column in R?

我想用一些约束来绑定 2 个不同长度的数据框,但我不确定该怎么做。在我 运行 代码之后,它说 "the numbers of columns of arguments do not match"

我想根据列名绑定两个不同的数据框。根据下面的示例数据,我想要一个组合数据框,使 dtf2 的行名成为第一列,而 dtf1 的第一列仍然保持不变。我在下面附上了我想要的预期输出的图表。

下面的代码是我的示例数据

a <- c(1,2,3,4,5,6,6,7,7)
b <- c(11,3,6.5,7,8,9,3,2,5)
dtf1 <- as.data.frame(rbind(a,b))
colnames(dtf1) <- c("aa","bb","cc","dd","ee","ff","gg","hh","ii")

c <- c(1,2,3,4,5,6,7,8)
d <-c(10,9,8,7,6,5,4,3)
dtf2 <- as.data.frame(rbind(c,d))
colnames(dtf2) <- c("bb","cc","dd","ee","ff","gg","hh","ii")

rbind(dtf1,dtf2)

这张图是我想要的预期输出:

您可以先 cbind dtf2 中的 rownamesrbind dtf1

rbind(dtf1, cbind(aa = rownames(dtf2), dtf2))

#  aa bb  cc dd ee ff gg hh ii
#a  1  2 3.0  4  5  6  6  7  7
#b 11  3 6.5  7  8  9  3  2  5
#c  c  1 2.0  3  4  5  6  7  8
#d  d 10 9.0  8  7  6  5  4  3

使用 dplyr,它不会直接将列强制转换为字符,因此您需要明确提及它。

library(dplyr)
bind_rows(dtf1 %>% mutate(aa = as.character(aa)), 
          bind_cols(aa = rownames(dtf2), dtf2))