[R] Rearrange Data Frame

Sarah Goslee sarah.goslee at gmail.com
Wed Jul 29 22:48:43 CEST 2015


Hi Stella,

On Wed, Jul 29, 2015 at 1:14 PM, Stella Xu <Stella.Xu at hli.ubc.ca> wrote:
>
> My question is about how to select and rearrange the data to a new data
> frame
> Here is an example:
> Samples  counts  time
> A                 10           3
> A                 12           4
> A                 11           3
> B                 12           4
> B                 10           5
> C                 11           2
> C                 13           3
> Say, if I want to make a new table that only look at “counts” as
> below:
> A        B       C
> 10     12     11
> 12     10     13
> 11
> How can I do this in R?
> Thank you!

Your example data doesn't use time at all, and contains a duplicate
pair of A,?,3 - what do you want to have happen there? How should
duplicates be handled? How should the ordering of values work? If
instead that should be a 5, here's something that is almost what you
want (but I find more useful):

x <- structure(list(Samples = c("A", "A", "A", "B", "B", "C", "C"),
    counts = c(10L, 12L, 11L, 12L, 10L, 11L, 13L), time = c(3L,
    4L, 5L, 4L, 5L, 2L, 3L)), .Names = c("Samples", "counts",
"time"), class = "data.frame", row.names = c(NA, -7L))

library(reshape2)
dcast(x, time ~ Samples, value.var="counts", sum)
  time  A  B  C
1    2  0  0 11
2    3 10  0 13
3    4 12 12  0
4    5 11 10  0

If you want the results "scooted up", I think there was recently a
discussion on this list on doing so.

Sarah
-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list