首页 > 解决方案 > 根据出现时间估算分类变量的 NA

问题描述

我有一个像下面这样的数据集,具有独特的公司年度观察结果。但是由于之前的合并,变量 IndustryCode 有一些 NA。

stkcd date industrycode
10    2002   .
10    2003   .
10    2004   E22
10    2005   E22
10    2006   E22
10    2007   E22
10    2008   G45
10    2009   G45
10    2010   .
10    2011   .
11    2001   .
11    2002   .
11    2003   D23
11    2004   D23
....

我想用同一家公司最近一年的价值来估算 NA。例如公司 10(stkcd=10),将 2004 年之前的 IndustryCode 更改为 E22,即 2004 年的值,将 2009 年之后的 NAs 替换为 G45,即 2009 年的值。

我怎样才能在 R 中实现这一点?

标签: rtime-seriesnaimputation

解决方案


如何从 应用两倍的na.locf功能zoo

基本上它NA用最后一个值代替,你也需要倒退。

一些数据:

dat <- data.frame(
  stkcd = rep(10, 10),
  year = 2002:2011,
  type = c(NA,NA, "E22", "E22","E22", "E22", "G45", "G45", NA, NA)
)


library(zoo)
dat$type <- na.locf(dat$type, na.rm = F) # computes NA with the last value found
dat$type <- na.locf(dat$type, na.rm = F, fromLast = T) # this because you start with NAs, so you need to go backwards too

# output:

# stkcd year type
# 1     10 2002  E22
# 2     10 2003  E22
# 3     10 2004  E22
# 4     10 2005  E22
# 5     10 2006  E22
# 6     10 2007  E22
# 7     10 2008  G45
# 8     10 2009  G45
# 9     10 2010  G45
# 10    10 2011  G45

如果您有多家公司,您首先需要group_bydplyr

library(dplyr)
library(zoo)

dat %>%
    group_by(stkcd) %>% # the variable used for the company name
    mutate(type = na.locf(type, na.rm = F),
           type = na.locf(type, na.rm = F, fromLast = T)) 

以 2 家公司为例:

dat <- data.frame(
  stkcd = c(rep(10, 10), rep(20,10)),
  year = rep(2002:2011, 2),
  type = c(NA,NA, "E22", "E22","E22", "E22", "G45", "G45", NA, NA,
           NA,NA, "E22", "E22","E22", "E22", "G45", "G45", NA, NA)
)

dat %>%
  group_by(stkcd) %>% # the variable used for the company name
  mutate(type = na.locf(type, na.rm = F),
         type = na.locf(type, na.rm = F, fromLast = T)) 

# A tibble: 20 x 3
# Groups:   stkcd [2]
# stkcd  year type 
# <dbl> <int> <fct>
#   1    10  2002 E22  
# 2    10  2003 E22  
# 3    10  2004 E22  
# 4    10  2005 E22  
# 5    10  2006 E22  
# 6    10  2007 E22  
# 7    10  2008 G45  
# 8    10  2009 G45  
# 9    10  2010 G45  
# 10    10  2011 G45  
# 11    20  2002 E22  
# 12    20  2003 E22  
# 13    20  2004 E22  
# 14    20  2005 E22  
# 15    20  2006 E22  
# 16    20  2007 E22  
# 17    20  2008 G45  
# 18    20  2009 G45  
# 19    20  2010 G45  
# 20    20  2011 G45  

推荐阅读