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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With