【发布时间】:2019-11-25 15:36:35
【问题描述】:
我正在尝试使用按日期索引的变量的最近可用版本来替换 x、q、z 的更新值。在 STATA 中,我们可以轻松地将其作为一个 for 循环来完成(参见下面的示例代码)。 STATA
- y指的是日期值20191125
local y 20191125
foreach v in attend child sibling{
replace `v'=`v'`y' if !missing(`v'`y')
}
数据
+----+----+---+-----------+-----------+-----------+
|attend | child | sibling | attend20191125 | child20191125 | sibling20191125 |
+----+----+---+-----------+-----------+-----------+
| 1 | 2 | 3 | 6 | 8 | 0 |
| 1 | NA | 0 | 1 | 1 | 1 |
| NA | 0 | 1 | 5 | 4 | 2 |
+----+----+---+-----------+-----------+-----------+
潜在输出:
+----+----+---+-----------+-----------+-----------+
|attend | child | sibling | attend20191125 | child20191125 | sibling20191125 |
+----+----+---+-----------+-----------+-----------+
| 1 | 2 | 3 | 6 | 8 | 0 |
| 1 |1 | 0 | 1 | 1 | 1 |
| 5 | 0 | 1 | 5 | 4 | 2 |
+----+----+---+-----------+-----------+-----------+
我知道如何从另一列替换一列的 NA 值。如何动态使用 purrr 做同样的事情?如何告诉 R 替换具有相同名称 + 日期前缀的变量中的值?我的数据集中有大约 25 个变量需要这个。
#Method 1: I can do it one variable at a time
df%<>%
mutate(attend=ifelse(is.na(attend)==T, attend20191125, attend),
child=ifelse(is.na(child)==T, child20191125, child),
sibling=ifelse(is.na(sibling)==T, sibling20191125, sibling))
#Method 2: using mutate_at (but not sure how I can dynamically refer to the date indexed variable?).
df%<>%
mutate_at(c("attend", "child", "sibling"), .=ifelse(is.na(.)==T, var20191125, .))
【问题讨论】:
-
是的,但我知道如何替换缺失值。我的问题更侧重于如何要求 R 替换新日期版本中的缺失值?
-
啊,现在清楚多了
标签: r if-statement tidyverse purrr dplyr