我知道并理解加法和减法之类的操作对于字符类和因子类数据都是无效的。我不明白的是为什么两种类型的 R 行为不同。
例如
#Creating character and factor
my_text<-c("This", "is", "text")
my_factor<-factor(c("This", "is", "factor"))
#This produces an error
my_text+1
#This produces "only" a warning and NA's
my_factor+1
我希望在这两种情况下都会出现一个简单的错误。我错过了什么?
最佳答案
这可能是因为调用的函数不一样。
正如您在算术运算符的帮助页面中所读:
The unary and binary arithmetic operators are generic functions: methods can be written for them individually or via the Ops group generic function
然后,如果您查看 S3 Group Generic Functions 帮助页面,在“Ops”段落下,您可以阅读:
For each argument its vector of classes is examined to see if there is a matching specific (preferred) or Ops method. If a method is found for just one argument or the same method is found for both, it is used. If different methods are found, there is a warning about ‘incompatible methods’: in that case or if no method is found for either argument the internal method is used.
因此,对于 my_factor
,Ops.factor
被调用(如您在警告消息中所见),在它的开头,您会发现:
ok <- switch(.Generic, `==` = , `!=` = TRUE, FALSE)
if (!ok) {
warning(gettextf("%s not meaningful for factors", sQuote(.Generic)))
return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2))))
}
这解释了执行 my_factor+1
而对于 my_text
,内部方法 (.Primitive("+")
) 被调用。 (要查看错误消息的实现位置,您必须深入研究 source code ,该消息位于第 511 行)。
关于r - 为什么二元运算符的错误消息因因子和字符而不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32888736/