我如何理解来自 rbind 的警告?

How do I understand the warnings from rbind?

如果我有两个具有相同列名的 data.frames,我可以使用 rbind 来制作一个数据框。但是,如果我有一个是因子,另一个是整数,我会收到这样的警告:

Warning message: In [<-.factor(*tmp*, ri, value = c(1L, 1L, 0L, 0L, 0L, 1L, 1L, : invalid factor level, NA generated

以下是问题的简化:

t1 <- structure(list(test = structure(c(1L, 1L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 2L), .Label = c("False", "True"), class = "factor")), .Names = "test", row.names = c(NA, 
-10L), class = "data.frame")
t2 <- structure(list(test = c(1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L
)), .Names = "test", row.names = c(NA, -10L), class = "data.frame")
rbind(t1, t2)

对于单列,这很容易理解,但是当它是十几个或更多因素的一部分时,就很难理解了。告诉我要查看哪一列的警告消息有什么用?除此之外,了解哪一列出错的好方法是什么?

您可以使用 classmapply 编写一个简单的小比较脚本,以比较 rbind 因数据类型不匹配而崩溃的位置,例如:

one <- data.frame(a=1,b=factor(1))
two <- data.frame(b=2,a=2)

common <- intersect(names(one),names(two))
mapply(function(x,y) class(x)==class(y), one[common], two[common])

#    a     b 
# TRUE FALSE 

根据 latemail 的回答,这里有一个比较两个 data.frames rbinding 的函数:

mergeCompare <- function(one, two) {
  cat("Distinct items: ", setdiff(names(one),names(two)), setdiff(names(two),names(one)), "\n")
  print("Non-matching items:")
  common <- intersect(names(one),names(two))
  print (mapply(function(x,y) {class(x)!=class(y)}, one[common], two[common]))
}