【问题标题】:Reformatting Panel Data according to a time and event variable根据时间和事件变量重新格式化面板数据
【发布时间】:2016-06-29 09:36:12
【问题描述】:

我有一个包含许多变量的面板数据集。三个最相关的变量是:“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" 

究竟是如何做到这一点的(请记住,我的数据集中还有很多其他解释变量)?

【问题讨论】:

    标签: r time panel-data


    【解决方案1】:
    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"  
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您可以使用 dplyr 和管道。如果您的数据始终按您的示例中的顺序排序,则此解决方案将起作用。

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

      【讨论】:

      • 这正是我想要的!谢谢
      猜你喜欢
      • 2011-08-12
      • 1970-01-01
      • 2018-02-05
      • 2012-10-29
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多