r - 在函数结果中抑制来自 attr() 的输出

标签 r attributes

data.frame 的源代码中,最后三行代码设置属性并返回结果。

    ...
    attr(value, "row.names") <- row.names
    attr(value, "class") <- "data.frame"
    value
}

在我写的一个函数中,结果是一个由 lapply 创建的命名列表。 .在函数体中设置任何属性之前,结果如下。
> x <- data.frame(a = 1:5, b = letters[1:5])    
> (g <- grep.dataframe("a|c", x))
# ...    
# $b
#   value row
# 1     a   1
# 2     c   3
> attributes(g)  # I want "list" in here...
# $names
# [1] "a" "b"

我希望将“class”包含在属性列表中,因此我添加了 attr(res, "class") <- "list" ( res 是最终结果)就在 res 之前. “class”现在显示在属性列表中。但是,它也会打印出我不想要的函数结果。我试着用 invisible 包裹它,但这没有用。

为什么手动分配的属性与函数结果一起打印,但在我创建的新数据框中被抑制?
> (h <- grep.dataframe("a|c", x))
# ...    
# $b
#   value row
# 1     a   1
# 2     c   3

# attr(,"class")  # ...This prints with the result. I don't want that.
# [1] "list"
> attributes(h)   # ...But I want these attributes
# $names
# [1] "a" "b"

# $class
# [1] "list"

最佳答案

?class文档提供了一些提示:

Many R objects have a class attribute, a character vector giving the names of the classes from which the object inherits. If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x) (except that integer vectors have implicit class "integer"). (Functions oldClass and oldClass<- get and set the attribute, which can also be done directly.)

When a generic function fun is applied to an object with class attribute c("first", "second"), the system searches for a function called fun.first and, if it finds it, applies it to the object. If no such function is found, a function called fun.second is tried. If no class name produces a suitable function, the function fun.default is used (if it exists). If there is no class attribute, the implicit class is tried, then the default method.


从中并运行一些简单的测试,我得出以下结论:
  • 列表是这些隐式类之一:参见 attributes(list(1)) , typeof(list(1))
  • print在列表上调用,它使用 print.default
  • print.default打印对象的属性

  • 所以你可以定义一个 print.list这将处理您的特殊情况:
     print.list <- function(x, ...) {
        if (is.list(x)) attr(x, "class") <- NULL
        print.default(x, ...)
     }
    
    res <- list(1)
    attr(res, "class") <- "list"
    res
    # [[1]]
    # [1] 1
    
    attributes(res)
    # $class
    # [1] "list"
    

    关于r - 在函数结果中抑制来自 attr() 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23885870/

    相关文章:

    r - 按元素名称组合/合并列表

    python - 攻击者 : Altering Default Order When Sorting by Object Attribute

    python - 重新排序类对象属性的最Pythonic方法是什么?

    r - 学习如何使用httr访问API的建议

    r - 将 LaTex 中的\to 符号放入 R 中的 ggplot2

    Azure GetBlobReference 属性后为空

    java - 使用 EL 对空属性进行快速失败的最简单方法?

    c# - 如何在 WebApi 中为属性实现 DI?

    删除字符串中空格后的所有内容

    r - 以给定格式转换数据框