开发者

R: Getting attribute values as a vector

开发者 https://www.devze.com 2023-04-11 21:26 出处:网络
I have a object with some attributes whose values are integers, i.e. h =: attr(,\"foo\") [1] 4 attr(,\"bar\")

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

精彩评论

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