gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:55:50 25 4
gpt4 key购买 nike

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com