R中带小数的POSIX变量的性能

Seb*_*ian 1 posix r

我刚刚意识到,对于带有两个小数位的POSIX变量,以下函数successor()显示出显着的性能损失.除此之外,for循环可能不是很好的r-style*.我很惊讶在我的系统中,带有两位小数的POSIX比没有小数的POSIX慢近30倍(20000步).带小数的POSIX甚至比仅将向量存储为字符要慢.

那个缓慢的性能是因为successor()函数?或者一般来说,更多的建议能否在R中将时间/日期变量存储为字符,并在真正需要时进行转换?

successor <- function(z) {
y<-as.vector(z)
for(i in 1:NROW(z)) {
y[i] <- if(i == NROW(z)) NA else z[i+1]
}
return(y)
}

u<-rep(strptime("15.01.2010 10:21:52.85",format="%d.%m.%Y %H:%M:%OS"),20000) # fragments of seconds stored
v<-seq(c(ISOdate(2011,09,12)),by="min", length.out=20000) # no fragments of seconds saved
u.posix.time.small<-system.time(successor(u[1:1000]))
u.char.time.small<-system.time(successor(as.character(u[1:1000])))
u.posix.time.big<-system.time(successor(u[1:20000]))
u.char.time.big<-system.time(successor(as.character(u[1:20000])))

v.posix.time.small<-system.time(successor(v[1:1000]))
v.char.time.small<-system.time(successor(as.character(v[1:1000])))
v.posix.time.big<-system.time(successor(v[1:20000]))
v.char.time.big<-system.time(successor(as.character(v[1:20000])))
rbind(u.posix.time.small,u.posix.time.big,u.char.time.small, u.char.time.big,v.posix.time.small, v.posix.time.big, v.char.time.small,v.char.time.big)[,1:3]
Run Code Online (Sandbox Code Playgroud)

*在绘图中使用段(x0 = x [i],x1 = x [i + 1],y0 = y [i],y1 = y [i + 1])时,我遇到了前任/成功的事情.无论如何,我想必须有另一种方式来解决后继者/前任,因为两次存储值似乎浪费了我.但我不是程序员只是用户.

And*_*rie 5

问题出在你的循环上,而不是数据类型.在R中,使用循环之前始终向量化函数.

以下是您的后继功能的替代配方,几乎没有时间运行.它只是删除向量的第一个元素,然后添加NA作为最后一个元素:

successor2 <- function(x){ c(x[-1], NA) }
Run Code Online (Sandbox Code Playgroud)

计时并显示结果是相同的:

> system.time(XX <- successor2(as.numeric(v)))
   user  system elapsed 
      0       0       0 
> system.time(YY <- successor(v))
   user  system elapsed 
   5.98    0.00    7.97 
> all.equal(XX, YY)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)