使用rbind连接具有零值的数据帧列表

时间:2016-11-22 02:46:26

标签: r rbind

我有一个我想要连接的数据框列表

 data List of 3  ###list of 3 dataframes

 AT1: 'data.frame': 1 obs of 2 varibles
 $neighbor: chr "ATa"
 $node: chr "AT1"

 AT2: 'data.frame': 0 obs of 2 varibles
 $neighbor: chr(0)
 $node: chr(0)

 AT3: 'data.frame': 4 obs of 2 varibles
 $neighbor: chr[1:4] "ATe" "ATf" "ATg" "ATh"
 $node: chr[1:4] "AT3" "AT3" "AT3" "AT3"

当我尝试使用

连接数据帧时
  concatdata<-do.call("rbind",data)

我得到以下

dataframe

node  neighbor

AT1       ATa
AT3       ATe
AT3       ATf
AT3       ATg
AT3       ATh

我希望零值数据帧包含如下。这是为了进一步计算。我怎么做?

节点邻居

AT1       ATa
AT2       0 or as NA
AT3       ATe
AT3       ATf
AT3       ATg
AT3       ATh   

1 个答案:

答案 0 :(得分:1)

我们可以创建if/else条件来创建0行到NA的数据集

do.call(rbind, lapply(data, function(x) 
    if(nrow(x)==0) data.frame(neighbour = NA, node = "AT2") else x))[2:1]

或另一种选择是加入

library(data.table)
rbindlist(data)[data.frame(node = names(data)), on = "node"]

数据

data <- structure(list(AT1 = structure(list(neighbour = "ATa", 
 node = "AT1"), .Names = c("neighbour", 
 "node"), row.names = c(NA, -1L), class = "data.frame"), AT2 = structure(list(
neigbour = character(0), node = character(0)), .Names = c("neigbour", 
 "node"), row.names = integer(0), class = "data.frame"), AT3 = structure(list(
neighbour = c("ATe", "ATf", "ATg", "ATh"), node = c("AT3", 
"AT3", "AT3", "AT3")), .Names = c("neighbour", "node"), row.names = c(NA, 
-4L), class = "data.frame")), .Names = c("AT1", "AT2", "AT3"))