subset() 删除向量上的属性;如何维护/持久化它们? [英] subset() drops attributes on vectors; how to maintain/persist them?
问题描述
假设我有一个向量,其中设置了一些属性:
Let's say I have a vector where I've set a few attributes:
vec <- sample(50:100,1000, replace=TRUE)
attr(vec, "someattr") <- "Hello World"
当我对向量进行子集化时,属性会被删除.例如:
When I subset the vector, the attributes are dropped. For example:
tmp.vec <- vec[which(vec > 80)]
attributes(tmp.vec) # Now NULL
有没有一种方法可以对属性进行子集化和持久化,而不必将它们保存到另一个临时对象?
Is there a way to, subset and persist attributes without having to save them to another temporary object?
奖励:在哪里可以找到这种行为的文档?
Bonus: Where would one find documentation of this behaviour?
推荐答案
我会为 [
或 subset()
写一个方法(取决于你如何设置子集)并安排它保留属性.这将需要一个 "class"
属性也添加到您的向量中,以便进行调度.
I would write a method for [
or subset()
(depending on how you are subsetting) and arrange for that to preserve the attributes. That would need a "class"
attribute also adding to your vector so that dispatch occurs.
vec <- 1:10
attr(vec, "someattr") <- "Hello World"
class(vec) <- "foo"
此时,子集删除属性:
> vec[1:5]
[1] 1 2 3 4 5
如果我们添加一个方法 [.foo
我们可以保留属性:
If we add a method [.foo
we can preserve the attributes:
`[.foo` <- function(x, i, ...) {
attrs <- attributes(x)
out <- unclass(x)
out <- out[i]
attributes(out) <- attrs
out
}
现在保留了所需的行为
> vec[1:5]
[1] 1 2 3 4 5
attr(,"someattr")
[1] "Hello World"
attr(,"class")
[1] "foo"
<小时>
以及奖金问题的答案:
And the answer to the bonus question:
来自 ?"["
在详细信息部分:
From ?"["
in the details section:
子集(空索引除外)将删除除名称、dim 和 dimnames 之外的所有属性.
这篇关于subset() 删除向量上的属性;如何维护/持久化它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!