R:每个比较对的整齐行

时间:2018-07-13 19:40:40

标签: r tidyr

我想收集每一对比较的行。换句话说,来自:

x=data.frame(id="Study1",
       t1=1,
       t2=2,
       t3=3,
       y2=0.1,
       y3=0.2,
       se2=0.5,
       se3=0.7)

收件人:

y=data.frame(id=c("Study1", "Study1"),
         t1=c(1,1),
         t2=c(2,3),
         y2=c(0.1,0.2),
         se2=c(0.5,0.7))

2 个答案:

答案 0 :(得分:1)

您可以使用reshape

n=length(grep("y",names(x)))
reshape(x,t(matrix(3:ncol(x),n)),idvar="id",dir="long")  
             id t1 time t2  y2 se2
Study1.1 Study1  1    1  2 0.1 0.5
Study1.2 Study1  1    2  3 0.2 0.7  

或者您可以使用:

library(data.table)
cbind(melt(setDT(x),"id",data.frame(matrix(3:ncol(x),2)),t1=x$t1)
           id variable value1 value2 value3 t1
    1: Study1        1      2    0.1    0.5  1
    2: Study1        2      3    0.2    0.7  1   


reshape(x,data.frame(matrix(3:ncol(x),2)),idvar="id",dir="long")
          id t1 time t2  y2 se2
    1 Study1  1    1  2 0.1 0.5
    2 Study1  1    2  3 0.2 0.7

答案 1 :(得分:0)

一种选择是将grouped的{​​{1}}个测量变量用作:

data.table::melt