r - 为什么二元运算符的错误消息因因子和字符而不同?

标签 r

我知道并理解加法和减法之类的操作对于字符类和因子类数据都是无效的。我不明白的是为什么两种类型的 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_factorOps.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/

相关文章:

R Shiny - 在侧边栏面板外显示静态文本

r - 获取Shiny中窗口的大小

r - 当数据更改时,ggvis 中的 linked_brush 无法在 Shiny 中工作

r - 具有透明度的重叠条形图

r - 将数据框摘要保存为数据框

r - 写为 "conditional or"运算符的 "short-circuit or"(也称为 `||` )如何在 R 中工作?

r - 包含字符串和数字的聚合数据框

保留 R 数据框中的行,这些行在列中包含特定模式

在 R 中删除过于常见的单词(出现在 80% 以上的文档中)

r - 如何在 R 中执行 Hartley 检验