Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pattern for `mutate()` with `if_any()` using {dplyr}
# 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