R reshape2 dcast: transform data

放肆的年华 提交于 2019-12-02 08:30:46

According to the documentation (?reshape2::dcast), dcast() allows for ... in the formula:

"..." represents all other variables not used in the formula ...

This is true for both the reshape2 and the data.table packages which both support dcast().

So, you can write:

reshape2::dcast(X, ... ~ TEST, value.var = "SCORE")
#  ID NAME    SEX  1  2  3
#1  1 MIKE   MALE 70 80 90
#2  2 LUCY FEMALE 65 75 NA

However, if the OP insists that the column names should be TEST_1, TEST_2, etc., the TEST column needs to be modified before reshaping. Here, data.table is used:

library(data.table)
dcast(setDT(X)[, TEST := paste0("TEST_", TEST)], ... ~ TEST, value.var = "SCORE")
#   ID NAME    SEX TEST_1 TEST_2 TEST_3
#1:  1 MIKE   MALE     70     80     90
#2:  2 LUCY FEMALE     65     75     NA

which is in line with the expected answer given as data.frame Y.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!