Tidyr - spreading multiple columns

I am preparing data for network meta-analysis and it is difficult for me to record 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 end this other?

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 am really stuck at this step and I am very grateful for the help ...

+3


source to share


1 answer


We can gather

"long" format, then unite

multiple columns on one and spread

onwide



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)

      

+3


source







All Articles