将数据帧中的值分配给R中的矩阵的最快方法

时间:2018-06-26 06:56:25

标签: r

我有一个非常大的数据框,其中Timestamp,StationId和Value作为列名。

我想创建一个新矩阵,其中行是Timestamps,列是StationIds,矩阵元素是Values。

我尝试使用循环来执行此操作,但这花费了很长时间:

for (row in 1:nrow(res)) 
{
rmatrix[toString(res[row,"Timestamp"]),toString(res[row,"StationId"])] <- 
res[row,"Value"]
}

The 'res' data frame looks like this.时间戳记为一年,间隔为5分钟。有62个唯一的工作站ID。 “值”列中的元素实际上是降雨值。

The rmatrix I'm trying to rearrange the data into looks like this.每行都是唯一的时间戳,间隔为5分钟。每列都是工作站的ID。矩阵的元素应该是当时该站的降雨值。

有更快的方法吗?

1 个答案:

答案 0 :(得分:0)

library(tidyverse)

df <- res %>% spread(StationIds,Values)