R: Getting attribute values ​​as a vector

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

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

And I want to get a vector type integer(2), v =:

[1] 4 2

I found two awkward ways to achieve this

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

or

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

The solution I'm looking for should just work in the main case described above, and should be as fast as possible.

+5
source share
1 answer

Well, if you can live with 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

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
+16
source

All Articles