【问题标题】:How to calculate transition probabilities in R如何计算R中的转移概率
【发布时间】:2020-09-24 11:24:03
【问题描述】:

我想按人年组合计算值之间的变化频率(面板数据)。这模仿了 Stata 的命令xttrans。不应包括索引 6 和 7 之间的转换,因为它不是一个人的转换。

df = data.frame(id=c(1,1,1,1,1,1,1,2,2,2,2,2,2,2), 
                year=seq(from=2003, to=2009, by=1), 
                health=c(3,1,2,2,5,1,1,1,2,3,2,1,1,2))

【问题讨论】:

    标签: r panel-data


    【解决方案1】:

    这是一个基本 R 解决方案,用于按 id 组计算转换计数:

    with(df, do.call(`+`, tapply(health, id, function(x){
      x <- factor(x, levels = min(health, na.rm = T):max(health, na.rm = T))
      table(x[-length(x)], x[-1])
    })))
    
    #    1 2 3 4 5
    #  1 2 3 0 0 0
    #  2 1 1 1 0 1
    #  3 1 1 0 0 0
    #  4 0 0 0 0 0
    #  5 1 0 0 0 0
    

    【讨论】:

    • 我正在尝试调整代码。问题出在我的真实数据中,我的数据不平衡。不同的出现次数和大量的 NA。
    • @MarcoDoe 我的代码可以处理不平衡的数据。至于NA,您没有提供示例,因此我不确定真实情况。
    • min() 和 max() 如果某些人没有健康数据,则会抛出错误。很抱歉在创建 MWE 时没有说得更清楚。
    【解决方案2】:
    library(tidyverse)
    
    # Calculate the last health status for each id
    df <- df %>% 
             group_by(id) %>% 
             mutate(lastHealth=lag(health)) %>%  
             ungroup()
    # Count nunmber of existing transitions
    transitions <- df %>% 
                      group_by(health, lastHealth) %>%  
                      summarise(N=n()) %>% 
                      ungroup()
    # Fill in the transition grid to include possible transitions that weren't observed
    transitions <- transitions %>% 
                     complete(health=1:5, lastHealth=1:5, fill=list(N=0))
    # Present the transitions in the required format
    transitions %>% 
      pivot_wider(names_from="health", values_from="N", names_prefix="health") %>%
      filter(!is.na(lastHealth))
    

    【讨论】:

    • 我不能使用pivot_wider。找出与旧 R 版本相关的原因stackoverflow.com/questions/56534005/…
    • 是的。 pivot_wider 相对较新。在旧版本中,函数为spread。在这种简单的情况下,转换应该很简单,但如果您无法弄清楚,请告诉我。我会提供一个替代方案。 [你对到目前为止的一切都满意吗?]
    • 我正在努力将所有内容调整为 n 维情况,包括潜在的 NA。
    • 我相信我的代码已经在health 中处理了NA。如果没有,请告诉我。如果多维是指“比id 更多的组变量”,那么修改两个group_bys 以在现在存在的前面包含其他变量。如果您的状态类别多于1:5,请相应修改complete() 中的两个1:5。
    • 它有效 :) 我实际上只需要创建过渡。 pivot_wider 使表格更具可读性,但也可以按行读取。
    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 2017-12-07
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多