问题描述
在data.frame
的源代码中,最后三行代码设置属性并返回结果.
In the source code for data.frame
, the last three lines of code set the attributes and return the result.
...
attr(value, "row.names") <- row.names
attr(value, "class") <- "data.frame"
value
}
在我编写的函数中,结果是由lapply
创建的命名列表.在函数主体中设置任何属性之前,结果如下.
In a function I wrote, the result is a named list created by lapply
. Before I set any attributes in the function body, result is as follows.
> 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"包含在属性列表中,所以我在res
之前添加attr(res, "class") <- "list"
(res
是最终结果).现在,类别"显示在属性列表中.但是,它也可以打印出我不想要的功能的结果.我尝试用invisible
包装它,但是没有用.
I'd like "class" to be included in the attributes list, so I add attr(res, "class") <- "list"
(res
is the final result) just before res
. "class" now shows up in the attributes list. However,it also prints out with the result of the function, which I don't want. I tried wrapping it with invisible
, but that didn't work.
为什么手动分配的属性随函数结果一起打印,但在我创建的新数据框中却被抑制?
Why do the manually assigned attributes print with the function result, but are suppressed in a new data frame I create?
> (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
文档提供了一些指针:
The ?class
documentation offers some pointers:
当将通用函数fun应用于具有类属性c("first","second")的对象时,系统搜索名为fun.first的函数,如果找到该函数,则将其应用于目的.如果找不到这样的函数,则尝试一个名为fun.second的函数.如果没有任何类名会产生合适的函数,则使用fun.default函数(如果存在).如果没有class属性,则尝试使用隐式类,然后使用默认方法.
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.
从那开始并运行一些简单的测试,我得到了这一点:
From that and running a few simple tests, I gather that:
- 列表是这些隐式类之一:请参见
attributes(list(1))
,typeof(list(1))
- 在列表上调用
print
时,它使用的是print.default
-
print.default
打印对象的属性
- a list is one of these implicit classes: see
attributes(list(1))
,typeof(list(1))
- when
print
is called on a list, it is usingprint.default
print.default
prints the attributes of an object
因此您可以定义一个print.list
来处理您的特殊情况:
So you could define a print.list
that will handle your special case:
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"
这篇关于抑制函数结果中attr()的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!