【问题标题】:indexing operation removes attributes索引操作删除属性
【发布时间】:2012-11-06 02:50:55
【问题描述】:

显然,用属性索引一个列表会返回一个没有属性的列表。

> l <- list(a=1:3, b=7)
> attr(l, 'x') <- 67
> l
$a
[1] 1 2 3

$b
[1] 7

attr(,"x")
[1] 67
> l[c('a','b')]
$a
[1] 1 2 3

$b
[1] 7

属性消失了。是否可以在保留列表属性的同时对列表进行索引?

【问题讨论】:

  • 这是记录在案的行为(参见?"[")。您可以编写自己的子集函数(或为其定义类和索引方法)。
  • @Roland 是的,它已记录在案。看起来唯一的选择就是你提到的那些。
  • 粘性包就是这样做的。

标签: r list attributes indexing


【解决方案1】:

这是一个子集函数。请注意,不要尝试覆盖“名称”属性,这一点很重要。

subset.with.attributes <- function(X, ...) {
 l <- X[...]
 attr.names <- names(attributes(X))
 attr.names <- attr.names[attr.names != 'names']
 attributes(l)[attr.names] <- attributes(X)[attr.names]
 return(l)
}

> subset.with.attributes(l, c('a','b'))
$a
[1] 1 2 3

$b
[1] 7

attr(,"x")
[1] 67

如果它实际上做了任何子集,尝试简单地分配属性将导致子集失败。

> subset.with.attributes(l, c('b'))
$b
[1] 7

attr(,"x")
[1] 67

【讨论】:

    【解决方案2】:

    使用sticky 包。它正是为此目的而设计的。 (完全披露:我是包作者。)使用简单,只需在您的矢量/列表/等上调用sticky()。例如:

    > l <- list(a=1:3, b=7)
    > attr(l, 'x') <- 67    
    > l <- sticky(l) 
    > attr(l,'x')  
    > [1] 67
    >
    > class(l)
    > [1] "sticky" "list" 
    

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 2014-09-01
      • 2013-11-04
      • 2018-02-03
      • 2014-01-23
      • 1970-01-01
      • 2023-03-15
      • 2017-09-20
      • 1970-01-01
      相关资源
      最近更新 更多