如何使用散列包的'values'函数取消分类元素?

时间:2014-02-02 18:47:29

标签: r

当我尝试从哈希中提取值时,使用values函数会丢失它们的类:

> h <- hash( c('a','b'), Sys.time() )
> h
<hash> containing 2 key-value pair(s).
  a : 2014-02-02 10:41:43
  b : 2014-02-02 10:41:43

> values( h )
           a          b 
  1391366503 1391366503 

> class( values(h) )
[1] "numeric"

但它们仍然是哈希中的正确类:

> class( h$a )
[1] "POSIXct" "POSIXt"
 > class( h$b )
[1] "POSIXct" "POSIXt" 

如何恢复值并保留其类?

1 个答案:

答案 0 :(得分:2)

?hash::values我们注意到有...个参数传递给sapplysapply然后,默认情况下将其“简化”参数设置为TRUE,调用simplify2array,其中日期格式在此行...as.vector(unlist(x, recursive = FALSE))...中更改为“数字”。< / p>

一个例子:

xx = c(Sys.time() + 1:3)
xx
#[1] "2014-02-02 21:54:01 EET" "2014-02-02 21:54:02 EET" "2014-02-02 21:54:03 EET"
sapply(xx, I)
#[1] 1391370842 1391370843 1391370844
sapply(xx, I, simplify = F)
#[[1]]
#[1] "2014-02-02 21:54:01 EET"    
#[[2]]
#[1] "2014-02-02 21:54:02 EET"    
#[[3]]
#[1] "2014-02-02 21:54:03 EET"

as.vector(xx)
#[1] 1391370842 1391370843 1391370844
typeof(xx)  #i.e. how "Date" class is stored internally
#[1] "double"
class(xx)
#[1] "POSIXct" "POSIXt" 
mode(xx)
#[1] "numeric"

要回答这个问题,解决办法可能是:

do.call(c, sapply(xx, I, simplify = F))
#[1] "2014-02-02 21:57:39 EET" "2014-02-02 21:57:40 EET" "2014-02-02 21:57:41 EET"

或者,如你所知:

Reduce(c, sapply(xx, I, simplify = F))
#[1] "2014-02-02 21:57:39 EET" "2014-02-02 21:57:40 EET" "2014-02-02 21:57:41 EET"

Reduce(c, values(h, simplify = F))
#[1] "2014-02-02 22:00:09 EET" "2014-02-02 22:00:09 EET"