2011-10-10 27 views
5

Ho un oggetto con alcuni attributi i cui valori sono interi, cioè h =:R: Come ottenere i valori degli attributi come un vettore

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

e voglio ottenere vettore di tipo integer(2), v =:

[1] 4 2 

ho trovato due modi maldestri per raggiungere questo

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

oppure:

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

La soluzione che sto cercando solo bisogno di lavorare per il caso base che ho descritto sopra e ha bisogno di essere il più veloce possibile.

risposta

16

Beh, se si può vivere con i nomi intatti:

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

In caso contrario (! Che in realtà è più veloce),

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

La performance è come segue:

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 
Problemi correlati