在R中按组转置数据 [英] Transpose data by groups in R
本文介绍了在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")
我想得到以下结果:
X Y 1 2 3
a e 10 20
a f 50
b c 40 30 60
b d 10 20
对于列 X
和的每种组合Y
我想按顺序在 D
列中转置 S
列中的数据。
For every combination of columns X
and Y
I would like to transpose data in column S
by order in column D
.
我认为 xtabs()
可以工作,但我认为不是,我最好的版本是:
I thought xtabs()
will work, but I don't think so, my best version is:
xtabs(formula=S~Y+D,data=x)
结果:
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")
如果要用 0填充空白条目
而不是 NA
(默认值),然后
If you want to fill empty entries with 0
instead of NA
(which is the default), then,
dcast(x, X + Y ~ D, value.var="S", fill=0)
这篇关于在R中按组转置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文