[R] reshape dataframe to array (pivot table)

Johannes Radinger JRadinger at gmx.at
Tue Jan 24 17:15:29 CET 2012


Hello,

I would like to reshape a dataframe into an array. This is kind a similar task as Excel performs with a Pivot table. To illustrate it:

LOC <- factor(c(1,2,2,3,1,1))
SPEC1 <- c(0,0,23,0,12,11)
SPEC2 <- c(1,2,0,0,0,4)

df <- data.frame(LOC,SPEC1,SPEC2) # original dataframe

a <- array(NA,dim=c(length(levels(LOC)),1,2),dimnames=list(levels(LOC),"LOC",c("SPEC1","SPEC2"))) #new array set up, how it should look like

The final array is splitted by the SPEC (for each SPEC an new layer), and
the LOC is collapsed so that there is only one line per level of LOC.
The array should get populated with:
1) the sums
2) and presence/absence (can be easily calculated from sums)

What is the best way to do that? I looked into reshape and apply...probably one of them is suitable but I don't know how...Or has that to be done with a loop?

cheers,
/johannes
-- 
"Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...



More information about the R-help mailing list