tidyr - spread multiple columns
Asked Answered
B

1

6

I'm preparing data for a network meta-analysis and I am having difficult in tyding the columns.

If I have this initial dataset:

Study Trt       y    sd   n
1       1   -1.22  3.70  54
1       3   -1.53  4.28  95
2       1   -0.30  4.40  76 
2       2   -2.60  4.30  71
2       4    -1.2   4.3  81

How can I finish with this other one?

Study Treatment1    y1  sd1  n1 Treatment2    y2  sd2  n2 Treatment3   y3 sd3 n3
    1     1          1 -1.22 3.70  54          3 -1.53 4.28  95         NA   NA  NA NA
    2     3          1 -0.30 4.40  76          2 -2.60 4.30  71          4 -1.2 4.3 81

I'm really stuck in this step, and I'd really appreciate some help...

Beeler answered 29/4, 2017 at 11:57 Comment(1)
I think your 'Treatment1' should be 1 1Capparidaceous
C
10

We can gather to 'long' format, then unite multiple columns to single and spread it to wide

library(tidyverse)
gather(df1, Var, Val,  Trt:n) %>%
      group_by(Study, Var) %>% 
      mutate(n = row_number()) %>%
      unite(VarT, Var, n, sep="") %>%
      spread(VarT, Val, fill=0)
Capparidaceous answered 29/4, 2017 at 12:5 Comment(2)
It's much better! however I need to handly replace the zeros in the absent trt 3 for study 1?Beeler
@Beeler I guess you can remove the fill=0 i.e. spread(VarT, Val)Capparidaceous

© 2022 - 2024 — McMap. All rights reserved.