25

可能重复:
这个 R 重塑应该很简单,但是

dcast来自reshape2没有公式且没有重复的作品。以这些示例数据为例:

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

我想要dcast这些数据,只是将值制成表格,而不对value.var包括 default 在内的任何函数应用任何函数length

在这种情况下,它工作正常。

> dcast(df, id~cat, value.var="val")
  id  SS   SV
1  A 220  224
2  B 222  225
3  C 223 2206

但是当有重复变量时,fun默认为length. 有没有办法避免它?

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))

> dcast(df2, id~cat, value.var="val")
Aggregation function missing: defaulting to length
  id SS SV
1  A  1  1
2  B  1  1
3  C  1  2

理想情况下,我正在寻找的是添加一个fun = NA,因为不要尝试聚合value.var. dcasting df2 时我想要的结果:

 id  SS  SV
1  A 220 224
2  B 222 225
3  C 223 220
4. C NA  1
4

2 回答 2

22

我不认为有办法直接做到这一点,但我们可以添加一个额外的列来帮助我们

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
于 2012-10-11T03:42:18.387 回答
9

当 Dason 回答我的问题时,我想出了相同的解决方案。

我意识到dcast根本不知道如何处理重复。我想出如何欺骗它的方法是添加另一个唯一标识符,这样它就不会被重复混淆。

在这个例子中:

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
于 2012-10-11T03:45:09.660 回答