仅在“夹在中间"的情况下填写NA使用dplyr设置相同的值 [英] NA filling only if "sandwiched" by the same value using dplyr
本文介绍了仅在“夹在中间"的情况下填写NA使用dplyr设置相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好,这是另一个缺少价值的问题.
Ok, here is yet another missing value filling question.
我正在寻找一种基于列中上一个和下一个存在的值来填充NA的方法.单一方向的标准填充不足以完成此任务.
I am looking for a way to fill NAs based on both the previous and next existent values in a column. Standard filling in a single direction is not sufficient for this task.
如果列中的上一个和下一个有效值不相同,则该块将保持为NA.
If the previous and next valid values in a column are not the same, then the chunk remains as NA.
示例数据框的代码为:
df_in <- tibble(id= 1:12,
var1 = letters[1:12],
var2 = c(NA,rep("A",2),rep(NA,2),rep("A",2),rep(NA,2),rep("B",2),NA))
谢谢
推荐答案
比较na.locf()
(最后观察到的结转)和na.locf(fromLast = TRUE)
(后退):
Comparing na.locf()
(last observation carried forward) and na.locf(fromLast = TRUE)
(backward):
mutate(df_in,
var_new = if_else(
zoo::na.locf(var2, na.rm = FALSE) ==
zoo::na.locf(var2, na.rm = FALSE, fromLast = TRUE),
zoo::na.locf(var2, na.rm = FALSE),
NA_character_
))
# # A tibble: 12 x 4
# id var1 var2 var_new
# <int> <chr> <chr> <chr>
# 1 1 a NA NA
# 2 2 b A A
# 3 3 c A A
# 4 4 d NA A
# 5 5 e NA A
# 6 6 f A A
# 7 7 g A A
# 8 8 h NA NA
# 9 9 i NA NA
# 10 10 j B B
# 11 11 k B B
# 12 12 l NA NA
这篇关于仅在“夹在中间"的情况下填写NA使用dplyr设置相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文