【问题标题】:How do fractions vectors (from MASS) have error checking?分数向量(来自 MASS)如何进行错误检查?
【发布时间】:2020-09-10 09:59:26
【问题描述】:

使用以下代码生成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) 是如何运行的?

【问题讨论】:

    标签: r types fractions r-s3


    【解决方案1】:

    fractions 有一个 S3 [&lt;- 方法:

    library(MASS)
    methods(class = "fractions")
    ## [1] [            [<-          as.character Math         Ops         
    ## [6] print        Summary      t           
    ## see '?methods' for accessing help and source code
    

    看看https://github.com/cran/MASS/blob/master/R/fractions.R的R源代码

    floor.rat 中调用,fractions[&lt;-.fractions 中调用,在[&lt;- 泛型中调用。

    > 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")
    

    【讨论】:

    • 真可惜。我想看看我是否可以很容易地让它给出 0/1 或 1/1 而不是 0 或 1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2013-03-15
    相关资源
    最近更新 更多