Skip to content
Prev 315831 / 398503 Next

Simple use of dcast (reshape2 package)

Hi,

This could be done with ?aggregate()
res<-aggregate(aa$Eaten,by=list(ID=aa$ID),FUN=function(x) x)
res1<-data.frame(ID=res[,1],data.frame(res[[2]]))
?names(res1)[2:3]<-unique(aa$Target)
?res1
#? ID TPP GPA
#1? 1?? 0?? 9
#2? 2?? 1? 11
#3? 3?? 3?? 8
#4? 4?? 1?? 8
#5? 5?? 2? 10
A.K.




----- Original Message -----
From: Patrick Connolly <p_connolly at slingshot.co.nz>
To: R-help <r-help at r-project.org>
Cc: 
Sent: Tuesday, January 22, 2013 4:23 AM
Subject: [R] Simple use of dcast (reshape2 package)

Suppose I have a small dataframe
? ?  Target Eaten ID
50? ? ? TPP? ?  0? 1
51? ? ? TPP? ?  1? 2
52? ? ? TPP? ?  3? 3
53? ? ? TPP? ?  1? 4
54? ? ? TPP? ?  2? 5
50.1? ? GPA? ?  9? 1
51.1? ? GPA? ? 11? 2
52.1? ? GPA? ?  8? 3
53.1? ? GPA? ?  8? 4
54.1? ? GPA? ? 10? 5

And I want to reshape it into 

? ID TPP GPA
1? 1?  0?  9
2? 2?  1? 11
3? 3?  3?  8
4? 4?  1?  8
5? 5?  2? 10

I realise that dcast function in the reshape2 package can handle much
more complicated tasks than that, but I can't make it do a simple one.

If I simply tried
Using ID as value column: use value.var to override.
Aggregation function missing: defaulting to length
? Eaten GPA TPP
1? ?  0?  0?  1
2? ?  1?  0?  2
3? ?  2?  0?  1
4? ?  3?  0?  1
5? ?  8?  2?  0
6? ?  9?  1?  0
7? ? 10?  1?  0
8? ? 11?  1?  0

As per the help file, it's giving counts of the numbers in the Eaten
column since that's the default fun.aggregate value.

My questions are: what fun.aggregate would work?? Alternatively, can
value.var be set to something useful?

TIA