Q:

How to choose columns with only NAs and a unique value and fill NA's with that value?

I have a data frame some columns of which have only a unique value or NA. I want to choose these columns and fill the NA's in these columns with the unique non-missing variable in the column.
Here is a mock-data: 
df = data.frame( A = c(1,NA,1,1,NA), B = c(2,NA,5,2,5), C =c(3,3,NA,NA,NA))
#df
#   A  B   C
#1  1  2   3
#2  NA NA  3
#3  1  5   NA
#4  1  2   NA
#5  NA 5   NA

I want to obtain: 
#df
#   A B   C
#1  1 2   3
#2  1 NA  3
#3  1 5   3
#4  1 2   3
#5  1 5   3

So far, I tried:
df = df %>% 
      map_if((length(unique(na.omit(.)))== 1), ~ unique(na.omit(.)))

df = df %>% 
     mutate_if((length(unique(na.omit(.)))== 1), ~ unique(na.omit(.)))

Both gave the following error:

Error in probe(.x, .p) : length(.p) == length(.x) is not TRUE

Can somebody please tell me what is the correct syntax to achieve what I want?

A:

We could check for condition in mutate_if and if it is satsfied then use the first non-NA value for entire column
library(tidyverse)

df %>%
  mutate_if(~n_distinct(.[!is.na(.)]) == 1, funs(.[!is.na(.)][1]))

#  A  B C
#1 1  2 3
#2 1 NA 3
#3 1  5 3
#4 1  2 3
#5 1  5 3

which could also be written as suggested by @RHertel
df %>% mutate_if(~n_distinct(.[na.omit(.)]) == 1, funs(na.omit(.)[1]))

To make it more clear we could create functions and use them accordingly
only_one_unique <- function(x) {
   n_distinct(x[!is.na(x)]) == 1
}

first_non_NA_value <- function(x) {
   x[!is.na(x)][1]
}

df %>%  mutate_if(only_one_unique, first_non_NA_value)

We could keep everything in base R using the same logic
only_one_unique <- function(x) {
   length(unique(x[!is.na(x)])) == 1
}

first_non_NA_value <- function(x) {
   x[!is.na(x)][1]
}

df[] <- lapply(df, function(x) if (only_one_unique(x)) 
                                   first_non_NA_value(x) else x)

