4

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

> 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

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

4

2 回答 2

4

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

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
于 2012-11-17T22:38:10.833 回答
1

使用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" 
于 2016-10-19T13:18:01.910 回答