简体   繁体   English

按R中的组转置数据

[英]Transpose data by groups in R

I have data in the following structure: 我有以下结构的数据:

x <- read.table(header=T, text="
X Y D S
a e 1 10
a e 2 20
a f 1 50
b c 1 40
b c 2 30
b c 3 60
b d 1 10 
b d 2 20")

And I want to get the following result: 我希望得到以下结果:

X Y   1   2   3
a e  10  20
a f  50
b c  40  30  60
b d  10  20

For every combination of columns X and Y I would like to transpose data in column S by order in column D . 对于列的每个组合XY我想转置中的列数据S通过顺序在列D

I thought xtabs() will work, but I don't think so, my best version is: 我认为xtabs()会起作用,但我不这么认为,我最好的版本是:

xtabs(formula=S~Y+D,data=x)

With result: 结果如下:

   D
Y    1  2  3
  c 40 30 60
  d 10 20  0
  e 10 20  0
  f 50  0  0
require(reshape2)
dcast(x, X + Y ~ D, value.var="S")

If you want to fill empty entries with 0 instead of NA (which is the default), then, 如果要用0而不是NA (这是默认值)填充空条目,那么,

dcast(x, X + Y ~ D, value.var="S", fill=0)

A solution in base R: 基础R的解决方案:

> reshape(x, timevar="D", idvar=c("X","Y"), direction="wide")
  X Y S.1 S.2 S.3
1 a e  10  20  NA
3 a f  50  NA  NA
4 b c  40  30  60
7 b d  10  20  NA

The other two answers are very good, but for what it's worth, since you mentioned you started your attempts with xtabs , you can get close to what you were looking for with a combination of xtabs and ftable . 另外两个答案非常好,但是对于它的价值,因为你提到你开始尝试使用xtabs ,你可以通过xtabsftable的组合接近你想要的ftable However, the result will include all factor levels 但是,结果将包括所有因子水平

ftable(xtabs(S ~ ., x))
#     D  1  2  3
# X Y           
# a c    0  0  0
#   d    0  0  0
#   e   10 20  0
#   f   50  0  0
# b c   40 30 60
#   d   10 20  0
#   e    0  0  0
#   f    0  0  0

Alternatively, you can do something like this: 或者,您可以执行以下操作:

data.frame(unique(x[1:2]), 
           as.data.frame.matrix(xtabs(S ~ do.call(paste, x[1:2]) + D, x)))
#   X Y X1 X2 X3
# 1 a e 10 20  0
# 3 a f 50  0  0
# 4 b c 40 30 60
# 7 b d 10 20  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM