如何用dplyr按组填充时间序列缺失年份的Value值为NaN?
补全分组缺失年份并填充NaN
原始数据
用户有如下tibble数据框:
library(tidyverse) # 生成数据 df <- tibble(ID = c(1, 1, 2, 2), Year = c(2000, 2003, 2000, 2003), Value = c(1, 1, 1, 1))
数据预览:
ID Year Value <dbl> <dbl> <dbl> 1 1 2000 1 2 1 2003 1 3 2 2000 1 4 2 2003 1
需求
数据缺失2001、2002、2004和2005年的记录,需按ID列分组补全这些缺失年份,并将对应Value列填充为NaN,期望输出如下:
wanted <- tibble(ID = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2), Year = c(2000, 2001, 2002, 2003, 2004, 2005, 2000, 2001, 2002, 2003, 2004, 2005), Value = c(1, NaN, NaN, 1, NaN, NaN, 1, NaN, NaN, 1, NaN, NaN))
输出预览:
ID Year Value <dbl> <dbl> <dbl> 1 1 2000 1 2 1 2001 NaN 3 1 2002 NaN 4 1 2003 1 5 1 2004 NaN 6 1 2005 NaN 7 2 2000 1 8 2 2001 NaN 9 2 2002 NaN 10 2 2003 1 11 2 2004 NaN 12 2 2005 NaN
解决方案
使用complete()函数即可实现需求,无需额外调用fill()。按ID分组后指定Year的目标序列,缺失的Value会自动填充为NA(数值型列中NA等价于NaN):
result <- df %>% group_by(ID) %>% complete(Year = seq(2000, 2005, 1)) %>% ungroup() # 查看结果 result
运行后输出与期望完全一致,缺失年份的Value列会显示为NaN(R中数值型NA打印时默认显示为NaN)。
内容的提问来源于stack exchange,提问作者Stefano Potter
相关产品推荐
相关产品推荐

