如何在不知道 data.frames 的长度的情况下使用不同的长度绑定 data.frames

How to cbind data.frames with differing lengths without knowing the lengths of the data.frames

我希望找到一种方法来 cbind data.frames 不同的长度,但我想 cbind data.frames 而不必指定长度。由于我将使用的 data.frames 的长度会有所不同,我不想在使用 cbind 之前找到长度。

我收到当前错误

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 8, 10

需要空白的输出

         A B
rwone    1 2
rwtwo    2 2
rwthree    3

NA 的期望输出

         A  B
rwone    1  2
rwtwo    2  2
rwthree  NA 3

我试过了

length(A) = length(B)

cbind(A,B)

我也试过了

if(length(A)<length(B)) {
     if(first==1) A = c(rep(NA, length(B)-length(A)),A);B=B
     if(first==0) A = c(A,rep(NA, length(B)-length(A)));B=B
} 

if(length(B)<length(A)) {
     if(first==1) B = c(rep(NA, length(A)-length(B)),B);A=A
     if(first==0) B = c(y,rep(NA, length(A)-length(B)));A=A
} 

cbind(A,B)

非常感谢任何帮助。

当您合并数据框的列而不是行名时,合并是最直接的。如果您将两个数据框中的列指定为与行名相同,则合并应该有效。这对我有用:

A = data.frame(A = c(1, 2))
B = data.frame(B = c(2,2,3))
A$key = row.names(A)
B$key = row.names(B)

merge(A, B, all = TRUE)

您还可以使用 plyr 库中的 join

library(plyr)
join(A, B, by = "key", type = "full")

使用基于 this post

的合并对 Nancy 的答案进行小幅修改
A = data.frame(A = c(1, 2))
B = data.frame(B = c(2,2,3))
A$key = 1:nrow(A)
B$key = 1:nrow(B)

merge(A, B, all = TRUE)