[R] How to re-arrange data in table?

Rene Braeckman RMan54 at cox.net
Thu Feb 15 20:22:07 CET 2007


I like to re-arrange a table (sTable) based on the value of one the rows
(Analyte) as shown below. Blocks of data with different values for Analyte
need to be stacked below each other. Any easy way to do this or any advice
where to look? 

Since it may be possible to get this in an earlier stage of the script, I
have added the R script that produces the original table below.
Thanks for any help.
Rene 


Original table (sTable): 
 
           1             2             3             4             5
6            
Analyte    "RBV"         "RBV"         "RBV"         "TBV"         "TBV"
"TBV"        
Dose       "200"         "400"         "600"         "200"         "400"
"600"        
AUC.n      "4"           "4"           "4"           "4"           "4"
"4"          
AUC.mean   " 44.023714"  " 77.853594"  "113.326952"  "  4.657904"  "
8.140416"  " 12.034377" 
...

Re-arranged table:

           1             2             3          
Analyte    "RBV"         "RBV"         "RBV"        
Dose       "200"         "400"         "600"        
AUC.n      "4"           "4"           "4"          
AUC.mean   " 44.023714"  " 77.853594"  "113.326952"  
...
Analyte    "TBV"         "TBV"         "TBV"        
Dose       "200"         "400"         "600"        
AUC.n      "4"           "4"           "4"          
AUC.mean   "  4.657904"  "  8.140416"  " 12.034377" 
...

The R script to produce the original table:

# Simulated simplified data
Subj  <- rep(1:4, each=6)
Analyte <- rep(c(rep("RBV",3),rep("TBV",3)),4)
Dose <- rep(c(200,400,600),8)
AUC <- rnorm(24, c(40,80,120,4,8,12), c(8,16,24,0.8,0.16,0.24))

# The real dataset may have NAs in it
df <- data.frame(Subj, Analyte, Dose, AUC)

myStats <- function(x) {
    count <- function(x) length(na.omit(x))
    pCV <- function(x) sd(x,na.rm=TRUE) / mean(x,na.rm=TRUE) * 100
    c(
      n = count(x),
      mean = mean(x,na.rm=TRUE),
      SD = sd(x,na.rm=TRUE),
      CV = pCV(x),
      median = median(x,na.rm=TRUE),
      min = min(x,na.rm=TRUE),
      max = max(x,na.rm=TRUE)
      )
}

library(doBy)
sData <- summaryBy(AUC ~ Analyte + Dose, data=df, FUN=myStats)
sTable <- t(sData)



More information about the R-help mailing list