R: Melt and Dcast

北城余情 提交于 2019-12-02 04:03:36

There are two issues here:

  1. Your data is already in long format but you have two value columns. The recent versions of data.table support multiple value vars in dcast().
  2. You need unique row ids within each group. Otherwise, dcast() will try to aggregate duplicates (using length() by default which explains the output you've got).

Please, try

library(data.table)   # version 1.10.4 used here
# coerce to data.table, add unique row numbers for each group
setDT(df)[, rn := rowid(CASE_ID)]
# dcast with multiple value vars
dcast(df, CASE_ID ~ rn, value.var = list("PERSON_ID", "PERSON_DIVISION"))
#   CASE_ID PERSON_ID_1 PERSON_ID_2 PERSON_ID_3 PERSON_DIVISION_1 PERSON_DIVISION_2 PERSON_DIVISION_3
#1:      C1           1           0          NA            Zone 1                NA                NA
#2:      C2           7           8           1            Zone 1            Zone 3            Zone 1
#3:      C3          20          NA          NA            Zone 5                NA                NA
#4:      C4           7          NA          NA            Zone 1                NA                NA

This can be written more concisely as a one-liner:

dcast(setDT(df), CASE_ID ~ rowid(CASE_ID), value.var = list("PERSON_ID", "PERSON_DIVISION"))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!