Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created January 19, 2022 09:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/08e042fa3888e12e3b1cc0d2dba634ff to your computer and use it in GitHub Desktop.
Save matt-dray/08e042fa3888e12e3b1cc0d2dba634ff to your computer and use it in GitHub Desktop.
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