tidyr - spread multiple columns

微笑、不失礼 提交于 2019-11-27 07:13:07

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/43695424/tidyr-spread-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!