Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
eold Avatar asked Oct 10 '11 23:10

eold


People also ask

What is attr () in R?

attributes(data) attr(x = data, which = "attribute_name") structure(data, dim = c(2, 6)) …and the functions can be defined as follows: Definitions: The attributes function returns or sets all attributes of a data object. The attr function returns or sets one specific attribute of a data object.

Can vectors have attributes in R?

Every vector can also have attributes, which you can think of as a named list of arbitrary metadata. Two attributes are particularly important. The dimension attribute turns vectors into matrices and arrays and the class attribute powers the S3 object system.

How do I get the attribute of an object in R?

Getting attributes of Objects in R Language – attributes() and attr() Function. attribute() function in R Programming Language is used to get all the attributes of data. This function is also used to set new attributes to data.


1 Answers

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
like image 193
Tommy Avatar answered Sep 22 '22 06:09

Tommy