【问题标题】:R: Tidy row for each comparison pairR:每个比较对的整齐行
【发布时间】:2018-07-13 19:40:39
【问题描述】:

我想为每对比较收集行。换句话说,从:

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

【问题讨论】:

  • 你怎么知道t1会被加倍并且没有pair列?
  • @CalumYou t1 加倍,因为它有两个比较:t1 vs t2,以及 t1 vs t3。
  • 好的,但是从数据来看,你怎么会知道呢?或者您对这些特定列名的硬编码解决方案是否满意?

标签: r tidyr


【解决方案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

【讨论】:

  • 谢谢,但这不适用于以下内容:x=data.frame(id="Study1", t1=1, t2=2, t3=3, t4=4, y2=0.1 , y3=0.2, y4=0.3, se2=0.5, se3=0.7, se4=0.9)
  • @jackonator 在这种情况下,您期望什么结果?您应该重塑数据。就是这样。在这种情况下,您需要有一种方法来识别重塑的方式
  • 在这种情况下,我希望: y=data.frame(id=c("Study1", "Study1", "Study1"), t1=c(1,1,1), t2 =c(2,3,4), y2=c(0.1,0.2,0.3), se2=c(0.5,0.7,0.9))
  • 在这种情况下,当使用reshape 替换为n 时,您将在上面包含2 的地方包含n=length(grep("y",names(x))); reshape(x,t(matrix(3:ncol(x),n)),idvar="id",dir="long"),它会起作用
【解决方案2】:

一种选择是使用grouped 测量data.table::melt 的变量作为:

library(data.table)


melt(setDT(x), id=1:2, measure=list(c("t2","t3"), c("y2","y3"), c("se2","se3")), 
                                  value.name=c("t2", "y2", "se2"))

#Or in short form
melt(setDT(x), id=1:2, measure=patterns("^t[2-3]", "^y", "^se"),
                       value.name=c("t2", "y2", "se2"))
#        id t1 variable t2  y2 se2
# 1: Study1  1        1  2 0.1 0.5
# 2: Study1  1        2  3 0.2 0.7

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多