R:将属性值作为向量

eol*_*old 6 attributes r vector

我有一个对象,其中一些属性的值为整数,即h =:

attr(,"foo")
[1] 4
attr(,"bar")
[1] 2
Run Code Online (Sandbox Code Playgroud)

我想获得类型的矢量integer(2),v =:

[1] 4 2
Run Code Online (Sandbox Code Playgroud)

我找到了两种笨拙的方法来实现这一目标

as.vector(sapply(names(attributes(h)), function(x) attr(h, x)))
Run Code Online (Sandbox Code Playgroud)

要么:

as.integer(paste(attributes(h)))
Run Code Online (Sandbox Code Playgroud)

我正在寻找的解决方案只需要为我上面描述的基本情况工作,并且需要尽可能快.

Tom*_*mmy 17

好吧,如果你能保持完整的名字:

> h <- structure(42, foo=4, bar=2)
> unlist(attributes(h))
foo bar 
  4  2 
Run Code Online (Sandbox Code Playgroud)

否则(实际上更快!),

> unlist(attributes(h), use.names=FALSE)
[1]  4 2
Run Code Online (Sandbox Code Playgroud)

表现如下:

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
Run Code Online (Sandbox Code Playgroud)