R Reshape gives "Error: index out of bounds"

R Reshape gives "Error: index out of bounds"

我在数据框中有一些数据,格式如下:

projectID counter type
 1           1     C
 1           2     D
 1           3     C
 2           1     E
 2           2     C
 2           3     D
 2           4     C

我正在尝试使用 reshape 将其转换为以下形式的数据框:

projectID 1  2  3  4 ...
 1        C  D  E  NA
 2        E  C  D  C
...

当我运行

x <- reshape(x,timevar = "counter",idvar = "projectID",direction = "wide")

我收到错误 Error: index out of bounds。我发现了一些错误报告(我不太明白)但是找不到关于这个问题的任何信息。对做同样事情的其他方式持开放态度。请注意,数据中没有 NA,但在转换为 wide 时当然会有(因为 'counter' 长度对于不同的项目是不同的)。

你可以试试

library(reshape2)
dcast(x, projectID~counter, value.var='type')
#  projectID 1 2 3    4
#1         1 C D C <NA>
#2         2 E C D    C

或者

library(tidyr)
spread(x, counter, type)