在 R 中按组重新填充缺少的日期年-月和值

如何解决在 R 中按组重新填充缺少的日期年-月和值

我正在尝试填写缺少的日期和费率。对于缺少的日期,我希望在 2019 年(一月)和 2021 年(一月)之间补充 yr_month。对于费率,我希望将任何缺失值重新填充为零。

我找到的最接近的例子在这里 - How to add only missing Dates in Dataframe 但我面临的挑战是我还有一个按组排列的列。这意味着每位患者将拥有 2 年的数据。

我能以有效的方式做到这一点的最佳方法是什么?

# A tibble: 10 x 3
# Groups:   clinic,yr_month [10]
   clinic   yr_month   rate
   <chr>    <chr>     <dbl>
 1 patient1 2019-01  0.528 
 2 patient1 2019-04  0.528 
 3 patient1 2020-05  0.528 
 4 patient1 2021-01  1.06  
 5 patient2 2019-01  0.0671
 6 patient2 2019-02  0.436 
 7 patient2 2019-03  0.805 
 8 patient2 2019-04  0.671 
 9 patient2 2019-05  0.268 
10 patient2 2019-06  0.101 

输入

structure(list(clinic = c("patient1","patient1","patient2","patient2"),yr_month = c("2019-01","2019-04","2020-05","2021-01","2019-01","2019-02","2019-03","2019-05","2019-06"
),rate = c(0.527704485488127,0.527704485488127,1.05540897097625,0.0671163461861136,0.436256250209739,0.805396154233364,0.671163461861136,0.268465384744455,0.10067451927917)),row.names = c(NA,-10L),groups = structure(list(clinic = c("patient1","2019-06"),.rows = structure(list(1L,2L,3L,4L,5L,6L,7L,8L,9L,10L),ptype = integer(0),class = c("vctrs_list_of","vctrs_vctr","list"))),class = c("tbl_df","tbl","data.frame"),.drop = TRUE),class = c("grouped_df","tbl_df","data.frame"))

预期输出:

# Groups:   clinic,yr_month 
   clinic   yr_month   rate
   <chr>    <chr>     <dbl>
 1 patient1 2019-01      0
 1 patient1 2019-02      0 
 1 patient1 2019-03      0
 1 patient1 2019-04  0.528
 1 patient1 2019-05      0
 1 patient1 2019-06      0 
 1 patient1 2019-07      0
 1 patient1 2019-08      0 
 1 patient1 2019-09      0
...
25 patient2 2019-01  0.0671
26 patient2 2019-02  0.436 
27 patient2 2019-03  0.805 
28 patient2 2019-04  0.671 
29 patient2 2019-05  0.268 
30 patient2 2019-06  0.101 
...
48 patient2 2021-01      0  
 

解决方法

使用 tidyversezoo,您可以尝试以下操作。您可以使用 group_by 来考虑诊所内的每位患者。对于日期,您可以使用 as.yearmon 中的 zoo 来使用年-月格式。然后,使用 complete 中的 tidyr,您可以用 0 填充缺失的 rate 值以表示缺失的月份。

library(tidyverse)
library(zoo)

df %>%
  group_by(clinic) %>%
  mutate(yr_month = as.yearmon(yr_month)) %>%
  arrange(yr_month) %>%
  complete(yr_month = seq(first(yr_month),last(yr_month),by = 1 / 12),fill = list(rate = 0)) 
,

首先,我们为您给定的月年组合创建一个空数据集:

library(dplyr)
library(tidyr)
library(purrr)
month_df <- tibble(
  month = rep(c(1:12),3),year = c(rep(2019,12),rep(2020,rep(2021,12))
  ) %>% 
  mutate(month_ind = ifelse(nchar(month) == 1,paste0("0",month),yr_month = paste0(year,"-",month_ind)) %>% 
  select(yr_month)

之后,给定 df 是您的数据:

df %>% ungroup() %>% 
  group_split(clinic) %>% 
  map(.,right_join,month_df) %>% 
  map(.,fill,clinic) %>% 
  bind_rows() %>% 
  arrange(clinic,yr_month) %>% 
  mutate(rate = ifelse(is.na(rate),rate))

输出为:

# A tibble: 72 x 3
   clinic   yr_month  rate
   <chr>    <chr>    <dbl>
 1 patient1 2019-01  0.528
 2 patient1 2019-02  0    
 3 patient1 2019-03  0    
 4 patient1 2019-04  0.528
 5 patient1 2019-05  0    
 6 patient1 2019-06  0    
 7 patient1 2019-07  0    
 8 patient1 2019-08  0    
 9 patient1 2019-09  0    
10 patient1 2019-10  0    
# ... with 62 more rows

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-