以下面的代码为例,生成一个 fractions
向量。
> example<-MASS:: as.fractions(c(0.2,0.4))
> example
[1] 1/5 2/5
如果我们把这些分数中的一个用字符串代替,我们就会得到以下错误。
> example[1]<-"0/1"
Error in floor(x) : non-numeric argument to mathematical function
这是怎么发生的?据我所知。fractions
向量不是S4对象,不应该有任何形式的错误检查,那么怎么会有 floor(x)
当我试图替换这样一个向量中的一个条目时,是否正在运行?
fractions
有一个S3 [<-
方法。
library(MASS)
methods(class = "fractions")
## [1] [ [<- as.character Math Ops
## [6] print Summary t
## see '?methods' for accessing help and source code
并看一下R的源代码: https:/github.comcranMASSblobmasterRfractions.R。
floor
中被调用。.rat
所谓 fractions
所谓 [<-.fractions
中被调用。[<-
通用。
> example[1] <- "0/1"
Error in floor(x) : non-numeric argument to mathematical function
> traceback()
5: matrix(floor(x))
4: .rat(x, cycles, max.denominator)
3: fractions(NextMethod())
2: `[<-.fractions`(`*tmp*`, 1, value = "0/1")
1: `[<-`(`*tmp*`, 1, value = "0/1")