for循环需要永远运行

时间:2014-09-29 11:30:52

标签: r performance for-loop rstudio

我有两张桌子。其中一个包含2012年至2014年的信息,期限为3小时。它看起来像这样:

                    B   C
1   01.06.2012 00:00    10  0   
2   01.06.2012 03:00    10  0   
3   01.06.2012 06:00    10  6   
4   01.06.2012 09:00    7,5 0   
5   01.06.2012 12:00    6   2,5 
6   01.06.2012 15:00    6   0   
7   01.06.2012 18:00    4   0   
8   01.06.2012 21:00    4   0   
9   02.06.2012 00:00    0   0   
10  02.06.2012 03:00    0   0 

另一张表是同一时间,但是按1分钟采样:

1   01.06.2012 00:00       
2   01.06.2012 00:01       
3   01.06.2012 00:01       
4   01.06.2012 00:03       
5   01.06.2012 00:03       
6   01.06.2012 00:05       
7   01.06.2012 00:05       
8   01.06.2012 00:07       
9   01.06.2012 00:08       
10  01.06.2012 00:09       
11  01.06.2012 00:10

现在,我需要将第二个表的第2行和第3行的值与第一个表相关联,以便第二个表中的时间戳位于第一个表的timestamp(i)timestamp(i+1)之间它会花费B(i)C(i)并复制它们。我有这个代码,我知道它有效,但运行它需要12个多小时,而且我需要以同样的方式处理许多这样的文件。

clouds <- read.csv('~/2012-2014 clouds info.csv', sep=";", header = FALSE)
cloudFull <- read.csv('~/2012-2014 clouds.csv', sep=";", header = FALSE)

for (i in 1:nrow(cloudFull)){
  dateOne <- strptime(cloudFull[i,1], '%d.%m.%Y %H:%M')

  for (j in 1:nrow(clouds)){
    bottomDate = strptime(clouds[j,1], '%d.%m.%Y %H:%M')
    upperDate = strptime(clouds[j+1,1], '%d.%m.%Y %H:%M')
    if  ((dateOne >= bottomDate) && (dateOne < upperDate)) {
      cloudFull[i,2] <- clouds[j,2]
      cloudFull[i,3] <- clouds[j,3]
      break

    } 

  }
}

write.csv(cloudFull, file = 'cc.csv')

现在如何让它跑得更快? object.size(cloudFull)39580744个字节提供了470000个行,但其他文件的数据量更多。我刚刚开始使用R(到目前为止已经工作了2天),我会用一种非常简单的语言对任何建议表示感谢:D

1 个答案:

答案 0 :(得分:4)

很难知道你的真实数据是什么样的,但是按照

的方式
full <- strptime(cloudFull[,1], '%d.%m.%Y %H:%M')
ref <- strptime(clouds[,1], '%d.%m.%Y %H:%M')
## ref <- sort(ref)
cloudsFull[, 2:3] <- clouds[findInterval(full, ref), 2:3]

使用findInterval()会将问题更改为线性扩展而非二次扩展的问题。

相关问题