作者celestialgod (攸蓝)
看板R_Language
标题Re: [问题] 拆解time-dependent的资料
时间Wed Apr 22 15:50:52 2015
※ 引述《yummy7922 (crucify)》之铭言:
: [问题类型]:
:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
:
: [软体熟悉度]:
: 请把以下不需要的部份删除
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 请简略描述你所要做的事情,或是这个程式的目的
: 资料是多个人的重复测量资料,每个人的观察笔数并不相同,
: 其中有一个会变动的变数(ex:用药资料,某几次有吃,某些次没有吃),
: 资料大概是长这样:
: ID M1 duration IS ID start stop M1 IS
: 1 1 1 0 1 0 1 1 0
: 1 0 2 0 1 1 4 0 1
: 1 0 3 0 2 0 3 1 0
: 1 0 4 1 2 3 5 0 0
: 2 1 1 0 3 0 1 1 0
: 2 1 2 0 ---> 3 1 2 0 1
: 2 1 3 0
: 2 0 4 0
: 2 0 5 0
: 3 1 1 0
: 3 0 2 1
: 资料中M1是会变动的变数,is是我的outcome,
: 希望可以转变成右方的样子,即,如果有资料变动就做纪录,
: 就是一般要处理time-dependent survival的样子,
: 目前只知道sas该怎麽处理,想来请教各位,
: R应该怎麽做转换,谢谢大家
I do not know whether there is a function to do this in R,
but I do this by dplyr.
library(data.table)
library(dplyr)
library(magrittr)
dat = data.frame(ID = rep(1:3, c(4, 5, 2)),
M1 = c(1,rep(0:1, each=3),0,0,1,0)) %>%
tbl_dt(FALSE) %>% group_by(ID) %>%
mutate(duration = 1:length(M1), IS = 0)
dat$IS[c(4, 11)] = 1
dat %>% group_by(ID) %>%
summarise(stop = cumsum(rle(M1)$lengths),
M1 = rle(M1)$values,
IS = IS[cumsum(rle(M1)$lengths)]) %>% group_by(ID) %>%
mutate(start = c(0, stop[1:(length(stop)-1)]))
ID stop M1 IS start
1 1 1 1 0 0
2 1 4 0 1 1
3 2 3 1 0 0
4 2 5 0 0 3
5 3 1 1 0 0
6 3 2 0 1 1
# update my code, 20150422 23:44
dat %>% group_by(ID) %>% {
tmp = use_series(., IS)
extract(.,, rle(M1), by =ID) %>% group_by(ID) %>%
mutate(start = c(0, cumsum(lengths)[-length(lengths)]),
stop = cumsum(lengths)) %>% ungroup() %>%
mutate(IS = tmp[cumsum(lengths)]) %>%
setnames("values", "M1") %>% select(-lengths)
}
ID M1 start stop IS
1 1 1 0 1 0
2 1 0 1 4 1
3 2 1 0 3 0
4 2 0 3 5 0
5 3 1 0 1 0
6 3 0 1 2 1
当然只要有group_by 都可以用tapply做,只是比较麻烦就不写了
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.205.27.107
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1429689054.A.45E.html
1F:→ obarisk: %<>%04/22 19:53
2F:→ celestialgod: 对吼,还有这个,谢谢提点04/22 20:19
※ 编辑: celestialgod (36.225.239.69), 04/22/2015 23:45:57