如果满足条件,我尝试将多个列中的值替换为 NA 。
这是一个示例数据集:
library(tidyverse)
sample <- tibble(id = 1:6,
team_score = 5:10,
cent_dept_test_agg = c(1, 2, 3, 4, 5, 6),
cent_dept_blue_agg = c(15:20),
num_in_dept = c(1, 1, 2, 5, 100, 6))
我希望当 num_in_dept 为 1 时,包含 cent_dept_.*_agg 的列为 NA,所以它看起来像这样:
library(tidyverse)
solution <- tibble(id = 1:6,
team_score = 5:10,
cent_dept_test_agg = c(NA, NA, 3, 4, 5, 6),
cent_dept_blue_agg = c(NA, NA, 17:20),
num_in_dept = c(1, 1, 2, 5, 100, 6))
我尝试过使用replace_with_na_at(来自nanier包)和 na_if (来自dplyr包),但我无法弄清楚。我知道我的选择标准是正确的(dplyr::matches("cent_dept_.*_agg"),但我无法找出解决方案。
在我的实际数据集中,我有许多以 cent_dept 开头并以 agg 结尾的列,因此选择与组件匹配的用户非常重要。
感谢您的帮助!