【问题标题】:Reshaping wide dataset in interval format以间隔格式重塑宽数据集
【发布时间】:2013-01-10 11:16:12
【问题描述】:

我正在研究一个“宽”数据集,现在我想使用一个特定的包(-msSurv-,用于非参数多状态模型),它需要区间形式的数据。

我当前的数据集的特点是每个人一行:

dat <- read.table(text = "

   id    cohort   t0    s1     t1     s2      t2     s3    t3
    1      2      0      1     50      2      70     4     100
    2      1      0      2     15      3      100    0     0   

", header=TRUE)

其中cohort 是一个时间固定的协变量,s1-s3 对应于随时间变化的协变量 s = 1,2,3,4 占用的值(它们是个体随时间访问的不同状态)。日历时间由t1-t3 定义,每个人的范围从0100

因此,例如,个人 1 停留在状态 = 1 直到日历时间 = 50,然后他停留在状态 = 2 直到时间 = 70,最后他停留在状态 = 4 直到时间 100。

我想得到的是一个“区间”形式的数据集,即:

id   cohort  t.start    t.stop   start.s   end.s          
1      2        0         50        1        2
1      2       50         70        2        4
1      2       70        100        4        4
2      1        0         15        2        3
2      1       15        100        3        3

我希望这个例子足够清楚,否则请告诉我,我会尽力进一步澄清。

您将如何使这种重塑自动化?考虑到我有相对大量的(模拟)个体,大约 100 万。

非常感谢您的帮助。

【问题讨论】:

  • 如果你在 *nix 机器上,我建议你看看 awk。

标签: r reshape


【解决方案1】:

我想我明白了。这行得通吗?

require(data.table)
dt <- data.table(dat, key=c("id", "cohort"))
dt.out <- dt[,  list(t.start=c(t0,t1,t2), t.stop=c(t1,t2,t3), 
                     start.s=c(s1,s2,s3), end.s=c(s2,s3,s3)), 
                     by = c("id", "cohort")]

#    id cohort t.start t.stop start.s end.s
# 1:  1      2       0     50       1     2
# 2:  1      2      50     70       2     4
# 3:  1      2      70    100       4     4
# 4:  2      1       0     15       2     3
# 5:  2      1      15    100       3     0
# 6:  2      1     100      0       0     0

如果您显示的输出确实是正确的并且是您所需要的,那么您可以再用两行获得(可能不是最好的方法,但它应该很快)

# remove rows where start.s and end.s are both 0
dt.out <- dt.out[, .SD[start.s > 0 | end.s > 0], by=1:nrow(dt.out)]
# replace end.s values with corresponding start.s values where end.s == 0
# it can be easily done with max(start.s, end.s) because end.s >= start.s ALWAYS
dt.out <- dt.out[, end.s := max(start.s, end.s), by=1:nrow(dt.out)]
dt.out[, nrow:=NULL]

> dt.out
#    id cohort t.start t.stop start.s end.s
# 1:  1      2       0     50       1     2
# 2:  1      2      50     70       2     4
# 3:  1      2      70    100       4     4
# 4:  2      1       0     15       2     3
# 5:  2      1      15    100       3     3

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2017-07-19
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多