I feel a bit stuck, and I am looking for a clever way to replace a specific NA value with a character. Any help or guidance is appreciated!
An example data.frame would look like this
library(tidyverse)
df <- tibble(genes=c("A","B","C"), x=c(NA,NA,4), y=c(NA,3,4))
df
#> # A tibble: 3 × 3
#> genes x y
#> <chr> <dbl> <dbl>
#> 1 A NA NA
#> 2 B NA 3
#> 3 C 4 4
Created on 2023-03-27 with reprex v2.0.2
I want to replace when gene==A the NA value in the x column with Yes. The rest of the values in the x column should remain the same. I tried with mutate and case_when(), but I am taking an error.
I want my date to look like this
#> # A tibble: 3 × 3
#> genes x y
#> <chr> <dbl> <dbl>
#> 1 A Yes NA
#> 2 B NA 3
#> 3 C 4 4
>Solution :
You could use an ifelse with is.na and condition on genes like this:
library(tidyverse)
df %>%
mutate(x = ifelse(is.na(x) & genes == 'A', 'Yes', x))
#> # A tibble: 3 × 3
#> genes x y
#> <chr> <chr> <dbl>
#> 1 A Yes NA
#> 2 B <NA> 3
#> 3 C 4 4
Created on 2023-03-27 with reprex v2.0.2