How to conditionally mutate multiple columns using “contains” and “ifelse”?

流过昼夜 提交于 2019-12-06 10:03:43

The issue with the vars(contains('account')) is that it matches all the columns where the substring 'account' is present and when we do the logical comparison, the 'low_account' column gets converted to NA because it is definitely lower or equal to 'low_account', thus only that NA replaced column is available. So, instead, we can get the columns of interest 'mid', 'median', 'mean' columns and then do the replace

library(tidyverse)
df %>% 
   mutate_at(vars(matches("(mid|mean|median)_account")),
           ~ replace(., .<= low_account | .>= high_account, NA))
# low_account high_account mid_account_0 mean_account_0 median_account_0 low_account.1 high_account.1 row.names
#1         1.0           16          8.50             NA              2.1           1.0             16      A001
#2         1.0           16          8.50             NA              3.8           1.0             16      A002
#3         0.5           56         28.25       30.19221             24.2           0.5             56      A003
#4         0.5           56         28.25       33.30556             24.2           0.5             56      A004
#5         0.5           56         28.25       31.17400             24.2           0.5             56      A005
#6         0.5           56         28.25       33.30556             24.2           0.5             56      A006
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!