Created
January 19, 2022 09:52
-
-
Save matt-dray/08e042fa3888e12e3b1cc0d2dba634ff to your computer and use it in GitHub Desktop.
Pattern for `mutate()` with `if_any()` using {dplyr}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Goal: put 1 in new col where 1 appears across other cols | |
library(dplyr) | |
df <- tibble( | |
x1 = c(1, NA, NA), | |
x2 = c(NA, 1, NA), | |
x3 = c(NA, 1, NA) | |
) | |
# # A tibble: 3 × 4 | |
# x1 x2 x3 | |
# <dbl> <dbl> <dbl> | |
# 1 1 NA NA | |
# 2 NA 1 1 | |
# 3 NA NA NA | |
df %>% | |
mutate( | |
xn = if_else( | |
if_any(x1:x3, ~ . == 1), | |
1, | |
NA_real_ | |
) | |
) | |
# # A tibble: 3 × 4 | |
# x1 x2 x3 xn | |
# <dbl> <dbl> <dbl> <dbl> | |
# 1 1 NA NA 1 | |
# 2 NA 1 1 1 | |
# 3 NA NA NA NA |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment