将长表更改为宽表

时间:2013-03-15 20:59:14

标签: r data-manipulation

假设我有一个像这样的长表:

A <- rep(c("a","b","c","d"),each=4)
B <- rep(c("e","f","g","h"),4)
C <- rep(c("i","j"),8)
D <- rnorm(16)
df <- data.frame(A,B,C,D)
head(df)

   A  B  C        D
1  a  e  i  -0.18984508
2  a  f  j  -1.82703822
3  a  g  i  -0.17307580
4  a  h  j  -1.38104238
5  b  e  i   0.08699983
6  b  f  j  -0.36442461

我想将长表更改为宽格式,以便A列和B列中的每个元素都是列的标题。每行应为1或0,表示元素是否存在。 C列和D列保持不变。所需的表格如下:

C           D a b e f g h
i -0.18984508 1 0 1 0 0 0
j -1.82703822 1 0 0 1 0 0
i -0.17307580 1 0 0 0 1 0
j -1.38104238 1 0 0 0 0 1
i  0.08699983 0 1 1 0 0 0
j -0.36442461 0 1 0 1 0 0

1 个答案:

答案 0 :(得分:5)

这是一种重塑形式,可以使用reshape2包来完成。

library("reshape2")
dcast(melt(df, id.vars=c("C", "D")), C+D~value, fun.aggregate=length)

给出了

   C           D a b c d e f g h
1  i -1.44485242 0 1 0 0 0 0 1 0
2  i -0.80834639 0 0 0 1 0 0 1 0
3  i -0.15202085 0 0 0 1 1 0 0 0
4  i -0.05626233 1 0 0 0 1 0 0 0
5  i  0.12031754 1 0 0 0 0 0 1 0
6  i  0.62206658 0 0 1 0 0 0 1 0
7  i  0.77101891 0 1 0 0 1 0 0 0
8  i  1.38752097 0 0 1 0 1 0 0 0
9  j -2.52137154 0 0 0 1 0 0 0 1
10 j -0.53231537 0 1 0 0 0 0 0 1
11 j -0.30178539 1 0 0 0 0 0 0 1
12 j -0.29823112 1 0 0 0 0 1 0 0
13 j -0.12988540 0 1 0 0 0 1 0 0
14 j  0.00517754 0 0 1 0 0 1 0 0
15 j  0.51452289 0 0 1 0 0 0 0 1
16 j  0.53260223 0 0 0 1 0 1 0 0

订单与原始数据集不同,但如果这很重要,请将订单列放入,通过,然后在最后对其进行排序。