Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

r - tidyr - spread multiple columns

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...