'Fill column with NA if all values are repeated in R

I have a dataframe with significant letters from an ANOVA test. I want to fill the letter column with NA only if all letters are equal (i.e., no significant differences).

I have tried:

library(dplyr)    
df<- data.frame(A=rnorm(5),B=rep("a",5))
df %>%  mutate(B = ifelse(length(unique(B)) == 1,NA, B))

this works for filling with NA but not for re-filling the column with old values:

df2<- data.frame(A=rnorm(5),B=c("b","a","ab","a","b"))
df2 %>%  mutate(B = ifelse(length(unique(B)) == 1,NA, B))
            A B
1  1.67671299 b
2  0.21659428 b
3 -1.50746338 b
4  0.82024729 b
5 -0.01105568 b 

Indeed, it does not fill it again with the original values. I also tried this but it does not work

df2 %>%   mutate_if((length(unique(.)) == 1),list(rep(NA,nrow(df))))
Error: `.p` is invalid.
x `.p` should have the same size as the number of variables in the tibble.
i `.p` is size 1.
i The tibble has 2 columns, non including the grouping variables.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source