在rbind.fill中指定“填充值”

时间:2017-04-03 13:45:06

标签: r dataframe rbind

ds2已包含NA。我想区分填充所产生的“已经存在”NA和NA。

library(plyr)
l <- LETTERS[]
ds1 <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],stringsAsFactors = F)
ds2 <- data.frame(a=NA,b=l[23], c=l[22],stringsAsFactors = F)

rbind.fill(ds1,ds2)

给出:

     a b c    d
1    A E G    J
2    B F H    K
3    C G I    L
4 <NA> W V <NA>

我希望如此:

     a b c    d
1    A E G    J
2    B F H    K
3    C G I    L
4 <NA> W V  foobar

我需要一个通用的解决方案,在绑定数据帧时设置一个特定的“填充值”。

我知道我可以像这样区分NA:

ds2[is.na(ds2)] <- "alreadyFooBar"
rbind.fill(ds1,ds2)

              a b c    d
1             A E G    J
2             B F H    K
3             C G I    L
4 alreadyFooBar W V <NA>

是否有可能反过来?

2 个答案:

答案 0 :(得分:1)

我认为这应该能满足您的需求:

library(plyr)
library(dplyr)
l <- LETTERS[]
ds1 <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],],stringsAsFactors = F)
ds2 <- data.frame(a=NA,b=l[23], c=l[22],stringsAsFactors = F)

NewCols <- setdiff(colnames(ds1),colnames(ds2))
ds2[NewCols] <- "fooBar"
rbind.fill(ds1,ds2)

给出:

     a b c      d
1    A E G      J
2    B F H      K
3    C G I      L
4 <NA> W V fooBar

答案 1 :(得分:0)

谢谢。我创造了我将来可以依赖的功能。即使两个输入都可能缺少列

fast.rbind <- function(x,y,value=NA){
    x[setdiff(colnames(y),colnames(x))] <- value

    y[setdiff(colnames(x),colnames(y))] <- value

    return(rbind(x,y))
}

x <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],stringsAsFactors = F)
y <- data.frame(a=NA, z=l[22],stringsAsFactors = F)
fast.rbind(x,y,"foobar")
相关问题