subset()丢弃矢量上的属性;如何维护/坚持他们? [英] subset() drops attributes on vectors; how to maintain/persist them?

查看:95
本文介绍了subset()丢弃矢量上的属性;如何维护/坚持他们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个向量,其中设置了一些属性:

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"

此时,子设置将删除属性:

At this point, subsetting removes attributes:

> 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
}

现在,所需的行为得以保留

Now the desired behaviour is preserved

> 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:

在详细信息部分的?"["中:

子集(空索引除外)将删除除名称,暗号和暗名之外的所有属性.

这篇关于subset()丢弃矢量上的属性;如何维护/坚持他们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆