Reputation: 1281
here is my 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
I want to get the table 1:
attitude count
a 235
b 223
c 173
d 82
e 50
f 9
And the table 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
How can i transform data.txt into the two tables?
Upvotes: 1
Views: 2717
Reputation: 77116
Using Hadley's packages,
plyr::ddply(d, .(attitude), summarise, n = sum(count))
reshape2::dcast(d, country ~ attitude)
Upvotes: 1
Reputation: 66874
Table 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
Table 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
Or if you are wanting a new 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
Upvotes: 4