Stack sets of three columns with means and confidence intervals for multiple samples

Viewed 274

I have an .csv output for two samples, with a few 'calculator' statistics calculated for each sample. Some 'calculators' have associated lower and higher confidence interval values. Eventually, I want to graph boxplots for all calculators with error bars for confidence intervals for those calculators that have them. But first, I need to manipulate the data into R-friendly format.

How do I take this input:

df <- data.frame(sample = as.factor(c("0.22um", "3um")),
                 nseqs = c(29445, 30212), coverage = c(0.96, 0.99),
                 invsimpson = c(20.36, 8.76), invsimpson_lci = c(19.99, 8.59), 
                 invsimpson_hci =c(20.76, 8.95),
                 shannon = c(3.75, 3.04), shannon_lci = c(3.73, 3.02), 
                 shannon_hci = c(3.77, 3.06))

Which looks like this:

  sample nseqs coverage invsimpson invsimpson_lci invsimpson_hci shannon shannon_lci shannon_hci
1 0.22um 29445     0.96      20.36          19.99          20.76    3.75        3.73        3.77
2    3um 30212     0.99       8.76           8.59           8.95    3.04        3.02        3.06

And convert it to this:

  sample calculator value  lci  hci
1 0.22um      nseqs   num <NA> <NA>
2 0.22um   coverage   num <NA> <NA>
3 0.22um invsimpson   num  num  num
4 0.22um    shannon   num  num  num
5    3um      nseqs   num <NA> <NA>
6    3um   coverage   num <NA> <NA>
7    3um invsimpson   num  num  num
8    3um    shannon   num  num  num

, where num are corresponding values from df. This data frame will have NA where the original df did not have confidence values for corresponding intervals

temp <- melt(df, id.vars= c("sample"), measure.vars=c("nseqs", "coverage", "invsimpson", "shannon"), variable.name="calculator")
partial.solution <- temp[with(base, order(group)), ]

will get values for all calculators but getting lci and hci to fall in line is a bit tricky.

A generic solution would be awesome. I expect matrices with hundreds of samples and variable number of calculators.

Thanks for all your help!

2 Answers
Related