这是我的data.txt:
country attitude count
china a 52
china b 58
china c 25
china d 12
china e 3
china f 1
france a 35
france b 48
france c 40
france d 21
france e 9
france f 2
india a 96
india b 28
india c 13
india d 7
india e 10
india f 0
england a 21
england b 41
england c 50
england d 23
england e 18
england f 3
usa a 31
usa b 48
usa c 45
usa d 19
usa e 10
usa f 3
我想得到表1:
attitude count
a 235
b 223
c 173
d 82
e 50
f 9
表2:
a b c d e f
china 52 58 25 12 3 1
france 35 48 40 21 9 2
india 96 28 13 7 10 0
england 21 41 50 23 18 3
usa 31 48 45 19 10 3
如何将data.txt转换为两个表?
答案 0 :(得分:4)
表1:
aggregate(count~attitude,data=data.txt,FUN=sum)
attitude count
1 a 235
2 b 223
3 c 173
4 d 82
5 e 50
6 f 9
表2:
xtabs(count~country+attitude,data.txt)
attitude
country a b c d e f
china 52 58 25 12 3 1
england 21 41 50 23 18 3
france 35 48 40 21 9 2
india 96 28 13 7 10 0
usa 31 48 45 19 10 3
或者,如果您想要一个新的data.frame:
reshape(data.txt,direction="wide",timevar="attitude",idvar="country")
country count.a count.b count.c count.d count.e count.f
1 china 52 58 25 12 3 1
7 france 35 48 40 21 9 2
13 india 96 28 13 7 10 0
19 england 21 41 50 23 18 3
25 usa 31 48 45 19 10 3
答案 1 :(得分:1)
使用Hadley的包,
plyr::ddply(d, .(attitude), summarise, n = sum(count))
reshape2::dcast(d, country ~ attitude)