r - r 在两列中估算缺失数据
问题描述
我有一个这样的数据集。
ID Yr Month
1 3 NA
2 4 23
3 NA 46
4 1 19
5 NA NA
我喜欢创建一个新列,Age
其中
Case1 : Age = Year, if Month is missing
Case2 : Age = Year + Month/12 , if Year and Month are not missing
Case3 : Age = Month/12 , if Year is missing
Case4 : Age = NA, if both Year and Month are missing.
最终的预期数据集应如下所示。
ID Yr Month Age
1 3 NA 3
2 4 23 5.91
3 NA 46 3.83
4 1 19 2.58
5 NA NA NA
我可以用 30 行代码来完成这项工作,但我正在寻找一个简单有效的解决方案来解决这个问题。任何建议,非常感谢,在此先感谢。
解决方案
您可以在case_when
声明中包含条件。
library(dplyr)
df %>%
mutate(Age = case_when(is.na(Month) & is.na(Yr) ~ NA_real_,
is.na(Month) ~ as.numeric(Yr),
is.na(Yr) ~ Month/12,
TRUE ~ Yr + Month/12))
# ID Yr Month Age
#1 1 3 NA 3.000000
#2 2 4 23 5.916667
#3 3 NA 46 3.833333
#4 4 1 19 2.583333
#5 5 NA NA NA
推荐阅读
- excel - Excel VBA ListBox (userform) - fmMultiSelectSingle 的多选问题
- javascript - 在对象中创建对象
- c++ - 我可以在源代码之外使用 Clang 库吗?
- jquery - 与 document.forms["id"]["name"].value 等效的 JQuery 是什么?
- java - CardView 和带有 TextView 子项的 LinearLayout 根本不显示
- python - 在 Python 中导入多个包宏
- python - Python/pandas:如何根据字符串条件递增每一行
- python - 最佳实践将数据框转换为字典?
- python - 努力创建数据框,ParserError:错误标记数据。C 错误:预计第 15 行中有 12 个字段,看到 16
- javascript - 使用 GatsbyJS 插件 gatsby-plugin-preload-fonts 的 Netlify 混合内容错误