开发者

R: Getting attribute values as a vector

I have a object with some attributes whose values are integers, i.e. h =:

attr(,"foo")
[1] 4
attr(,"bar")
[1] 2

An开发者_运维知识库d I want to get vector of type integer(2), v =:

[1] 4 2

I have found two clumsy ways to achieve this

as.vector(sapply(names(attributes(h)), function(x) attr(h, x)))

or:

as.integer(paste(attributes(h)))

The solution I am looking for just needs to work for the basic case I described above and needs to be as fast as possible.


Well, if you can live with the names intact:

> h <- structure(42, foo=4, bar=2)
> unlist(attributes(h))
foo bar 
  4  2 

Otherwise (which is actually faster!),

> unlist(attributes(h), use.names=FALSE)
[1]  4 2

The performance is as follows:

system.time( for(i in 1:1e5) unlist(attributes(h)) )                  # 0.39 secs
system.time( for(i in 1:1e5) unlist(attributes(h), use.names=FALSE) ) # 0.25 secs
system.time( for(i in 1:1e5) as.integer(paste(attributes(h))) )       # 1.11 secs
system.time( for(i in 1:1e5) as.vector(sapply(names(attributes(h)), 
             function(x) attr(h, x))) )                               # 6.17 secs
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜