Can dcast be used without an aggregate function? [duplicate]

本秂侑毒 提交于 2019-11-27 01:20:56

I don't think there is a way to do it directly but we can add in an additional column which will help us out

df2 <- structure(list(id = c("A", "B", "C", "A", "B", "C", "C"), cat = c("SS", 
"SS", "SS", "SV", "SV", "SV", "SV"), val = c(220L, 222L, 223L, 
224L, 225L, 220L, 1L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA, 
-7L))

library(reshape2)
library(plyr)
# Add a variable for how many times the id*cat combination has occured
tmp <- ddply(df2, .(id, cat), transform, newid = paste(id, seq_along(cat)))
# Aggregate using this newid and toss in the id so we don't lose it
out <- dcast(tmp, id + newid ~ cat, value.var = "val")
# Remove newid if we want
out <- out[,-which(colnames(out) == "newid")]
> out
#  id  SS  SV
#1  A 220 224
#2  B 222 225
#3  C 223 220
#4  C  NA   1

I figured out the same solution while Dason was answering mine.

I realized that dcast simply does not know how to deal with duplicates. The way I figured out how to trick it was by adding another unique identifer so it doesn't get confused by duplicates.

In this example:

df <- ddply(df2, .(cat), function(x){ x$id2 = 1:nrow(x); x})
>  dcast(df, id+id2~cat, value.var="val")[,-2]
  id  SS  SV
1  A 220 224
2  B 222 225
3  C 223 220
4  C  NA   1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!