从底部按列绑定不同长度的数据框

时间:2017-08-11 11:13:42

标签: r na fill cbind

我正在寻找从底部开始绑定不同长度数据帧的选项(最好使用基数R)。剩余/缺失的行应为NA d out。例如:

set.seed(1212)
a = as.data.frame(rnorm(1, 0, 1))
b = as.data.frame(rnorm(4, 0, 1))
c = as.data.frame(rnorm(3, 0, 1))

预期产出:

  rnorm(1, 0, 1) rnorm(4, 0, 1) rnorm(3, 0, 1)
1 NA               1.8374224       NA
2 NA               0.3436815       0.03719874
3 NA              -1.3600955      -1.92311898
4 -0.6290858       0.5358145       0.41087971

3 个答案:

答案 0 :(得分:2)

首先,评估要绑定的列的最大长度。

lenMax <- max(length(a[,1]), length(b[,1]), length(c[,1]))

然后,使用此长度使用NA填充新data.frame的列,以便它们适合。

data.frame(a = c(rep(NA, lenMax - length(a[,1])), a[,1]), 
           b = c(rep(NA, lenMax - length(b[,1])), b[,1]), 
           c = c(rep(NA, lenMax - length(c[,1])), c[,1]))

#            a          b           c
# 1         NA  1.8374224          NA
# 2         NA  0.3436815  0.03719874
# 3         NA -1.3600955 -1.92311898
# 4 -0.6290858  0.5358145  0.41087971

答案 1 :(得分:2)

您可以使用smartbind()

gtools::smartbind(a,b,c)
#    rnorm(1, 0, 1) rnorm(4, 0, 1) rnorm(3, 0, 1)
#1       -0.6290858             NA             NA
#2:1             NA      1.8374224             NA
#2:2             NA      0.3436815             NA
#2:3             NA     -1.3600955             NA
#2:4             NA      0.5358145             NA
#3:1             NA             NA     0.03719874
#3:2             NA             NA    -1.92311898
#3:3             NA             NA     0.41087971

答案 2 :(得分:1)

我们可以使用rowr

library(rowr)
 apply(rowr::cbind.fill(a, b, c, fill = NA), 2, function(x) x[order(!is.na(x))])
#    rnorm.1..0..1. rnorm.4..0..1. rnorm.3..0..1.
#[1,]             NA      1.8374224             NA
#[2,]             NA      0.3436815     0.03719874
#[3,]             NA     -1.3600955    -1.92311898
#[4,]     -0.6290858      0.5358145     0.41087971