eold
eold

Reputation: 6042

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

And 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.

Upvotes: 6

Views: 13472

Answers (1)

Tommy
Tommy

Reputation: 40803

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

Upvotes: 18

Related Questions