An alternative solution that uses two intermediate variables:
q_na number of NA per row
s_row sum of the row values excluding NA.
library(tidyverse)
df <- tribble(
~col_1, ~col_2, ~col_3,
NA, 1, 3,
NA, NA, 2,
1, 5, 6,
NA, NA, NA,
3, NA, 2)
df %>%
rowwise() %>%
mutate(q_na = sum(is.na(c_across(col_1:col_3))),
s_row = sum(c_across(col_1:col_3), na.rm = TRUE)) %>%
ungroup() %>%
filter(q_na == 1) %>%
mutate(across(col_1:col_3, ~if_else(is.na(.x), s_row, .x))) %>%
dplyr::select(col_1:col_3)
#> # A tibble: 2 x 3
#> col_1 col_2 col_3
#> <dbl> <dbl> <dbl>
#> 1 4 1 3
#> 2 3 5 2
If you want to get all rows, just delete the filter and include it in the if_else:
df %>%
rowwise() %>%
mutate(q_na = sum(is.na(c_across(col_1:col_3))),
s_row = sum(c_across(col_1:col_3), na.rm = TRUE)) %>%
ungroup() %>%
filter() %>%
mutate(across(col_1:col_3,
~if_else(q_na == 1 & is.na(.x), s_row, .x))) %>%
dplyr::select(col_1:col_3)
#> # A tibble: 5 x 3
#> col_1 col_2 col_3
#> <dbl> <dbl> <dbl>
#> 1 4 1 3
#> 2 NA NA 2
#> 3 1 5 6
#> 4 NA NA NA
#> 5 3 5 2
Created on 2021-06-05 by the reprex package (v0.3.0)