Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
rbind基于列名称,不排除不匹配项_R - Fatal编程技术网

rbind基于列名称,不排除不匹配项

rbind基于列名称,不排除不匹配项,r,R,样本数据: l <- list(x=data.frame(X1=1,X2=2,X3=3,X4=4,X5=5), y=data.frame(X1=6,X8=7,X4=8,X9=9,X5=10), z=data.frame(X1=11,X2=12,X3=13,X4=14,X5=15) ) 所需的输出应为data.frame: X1 X2 X3 X4 X5 1 2 3 4 5 11 12 13

样本数据:

l <- list(x=data.frame(X1=1,X2=2,X3=3,X4=4,X5=5),
          y=data.frame(X1=6,X8=7,X4=8,X9=9,X5=10),
          z=data.frame(X1=11,X2=12,X3=13,X4=14,X5=15)
          )
所需的输出应为
data.frame

  X1  X2  X3  X4  X5
   1   2   3   4   5
  11  12  13  14  15
编辑:也许像这样:

do.call(rbind, lapply(l, function(x) x[!any(is.na(match(c("X1","X2","X3","X4","X5"), names(x))))]))

这里有一种方法:

match_all_columns <- function (d, col) {
  if (all(names(d) %in% col)) {
    out <- d[, col]
  } else {
    out <- NULL
  }
  out
}
# or as a one-liner
match_all_columns <- function (d, col) if (all(names(d) %in% col)) d[col]

matched_data <- lapply(l, match_all_columns, col)
result <- do.call(rbind, matched_data)
result
#   X1 X2 X3 X4 X5
# x  1  2  3  4  5
# z 11 12 13 14 15

匹配所有列这似乎也起作用了:

do.call(rbind, lapply(l, function(x) x[!any(is.na(match(c("X1","X2","X3","X4","X5"), names(x))))]))

另一种可能性是允许列顺序发生变化:

output.df <- data.frame(X1=numeric(), X2=numeric(), X3=numeric(),
                        X4=numeric(), X5=numeric())

for(i in seq_along(l)) {
    if(identical(sort(colnames(l[[i]])),sort(colnames(output.df))))
        output.df[nrow(output.df)+1,] <- l[[i]][,colnames(output.df)]
}

output.df

#   X1 X2 X3 X4 X5
# 1  1  2  3  4  5
# 2 11 12 13 14 15

output.df使用
data.table的另一个选项

library(data.table)#v1.9.5+
na.omit(rbindlist(l, fill=TRUE)[,col, with=FALSE])
#   X1 X2 X3 X4 X5
#1:  1  2  3  4  5
#2: 11 12 13 14 15

是否有列名为
c(col,somethingElse)
的条目?i、 e.有冗余列的条目。@朱利叶斯,不,不可能。不匹配的列表必须完全排除。仅供参考,两个解决方案都已发布忽略列顺序是的,我只是注意到了这一点。谢谢你指出这一点。对我来说,这似乎是一个非常简单的句子!“你觉得这有什么坏处吗?”多米尼克托伊斯,不,我没看到。是的,恐怕不是所有情况下都能用。那么警告是什么呢?这是一个诚实的问题,我也看不出有什么缺点,只是想知道为什么你最后没有选择那个答案。。。。但你说它并不是在所有情况下都有效吗?@DominicComtois我认为这可能比我在一个有大量行的数据帧中的解决方案慢得多。行切片在R慢。哦,我不会接受我的答案!我很高兴看到其他解决方案,我可以从中学习。谢谢
library(data.table)#v1.9.5+
na.omit(rbindlist(l, fill=TRUE)[,col, with=FALSE])
#   X1 X2 X3 X4 X5
#1:  1  2  3  4  5
#2: 11 12 13 14 15