我有一个包含许多变量的面板数据集。三个最相关的变量是:" cid" (国家代码),'时间" (0-65)和"事件" (0,1,2,3,4,5,6)。
我正在尝试运行cox回归(使用coxph
),但是,由于时间变量对于每个国家/地区都有不同的起点和终点,因此我需要先创建一个开始时间和结束时间变量。这是我遇到问题的地方。
以下是三个主要变量的样本:
> data
cid time event
[1,] "AFG" "20" "0"
[2,] "AFG" "21" "0"
[3,] "AFG" "22" "0"
[4,] "AFG" "23" "0"
[5,] "AFG" "24" "0"
[6,] "AFG" "25" "0"
[7,] "AFG" "26" "1"
[8,] "AFG" "27" "1"
[9,] "AFG" "28" "1"
[10,] "AFG" "29" "1"
我们的想法是将这些数据转换为以下内容:
> data
cid time1 time2 event
[1,] "AFG" "20" "25" "0"
[2,] "AFG" "26" "29" "1"
如何做到这一点(请记住我的数据集中有很多其他解释变量)?
答案 0 :(得分:1)
您可以使用dplyr和pipe。如果您的数据始终按照示例顺序排序,则此解决方案将起作用。
data<-data.frame(cid=rep("AFG",10),time=seq(20,29,1),event=c(0,0,0,0,0,0,1,1,1,1))
library(dplyr)
data %>% group_by(cid,event) %>%
summarise(time1=min(time),time2=max(time))
答案 1 :(得分:0)
subset1<- data[data$event==0,]
subset1
subset2<- data[data$event==1,]
subset2
s1<- cbind(cid="AFG",time1=min(subset1$time),time2=max(subset1$time),event = 0)
s1
s2<- cbind(cid="AFG",time1=min(subset2$time),time2=max(subset2$time),event = 1)
s2
data1=rbind(s1,s2)
data1
# cid time1 time2 event
# [1,] "AFG" "20" "25" "0"
# [2,] "AFG" "26" "29" "1"
希望这会有所帮助。