Reputation: 3088
I have an example data.frame that looks like this:
rep = c(1,2,3,1,2,3)
day = c(0,0,0,1,1,1)
trt1= c(10,10,20,10,10,20)
trt2=c(10,10,20,10,10,20)
trt3 = c(10,10,20,10,10,20)
exam = data.frame(rep,day,trt1,trt2,trt3)
exam
rep day trt1 trt2 trt3
1 1 0 10 10 10
2 2 0 10 10 10
3 3 0 20 20 20
4 1 1 10 10 10
5 2 1 10 10 10
6 3 1 20 20 20
I would like to use tidyR to bring it in this form
rep Treatments 0 1
1 trt1 10 10
1 trt2 10 10
1 trt3 10 10
2 trt1 10 10
2 trt2 10 10
2 trt3 10 10
where I mainly bring the days as columns
Any help or direction are appreciated
Upvotes: 0
Views: 47
Reputation: 101403
A data.table
option with dcast
+ melt
> dcast(melt(setDT(exam), id = 1:2), rep + variable ~ day)
rep variable 0 1
1: 1 trt1 10 10
2: 1 trt2 10 10
3: 1 trt3 10 10
4: 2 trt1 10 10
5: 2 trt2 10 10
6: 2 trt3 10 10
7: 3 trt1 20 20
8: 3 trt2 20 20
9: 3 trt3 20 20
Upvotes: 1
Reputation: 39595
Maybe this can help:
library(dplyr)
library(tidyr)
#Code
new <- exam %>%
pivot_longer(-c(1,2)) %>%
pivot_wider(names_from = day,values_from=value)
Output:
# A tibble: 9 x 4
rep name `0` `1`
<dbl> <chr> <dbl> <dbl>
1 1 trt1 10 10
2 1 trt2 10 10
3 1 trt3 10 10
4 2 trt1 10 10
5 2 trt2 10 10
6 2 trt3 10 10
7 3 trt1 20 20
8 3 trt2 20 20
9 3 trt3 20 20
Upvotes: 2