Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace a specific NA value with a character in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading