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 NA with text for specific ids

Based on the code and data below how can I replace NAs in column a with Transportation Element Maps 2012 based on specific ids in column id?

Code:

# Sample df
df = structure(list(id = c(1, 2, 3, 4, 5, 6, 7), a = c("a", "Transportation Element Maps 2012", NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-7L))

# Desired df
df1 = structure(list(id = c(1, 2, 3, 4, 5, 6, 7), a = c("a", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", NA)), class = "data.frame", row.names = c(NA, 
-7L))

# Current approach which throws an error
df1 = df %>% ifelse(id %in% 3:6) %>%  mutate(a %in% NA, "Transportation Element Maps 2012")

# Error
Error in ifelse(., reference_number %in% 3:6) : 
  'list' object cannot be coerced to type 'logical'

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

>Solution :

Use is.na to find NA elements that returns a logical vector, as well as keep the id %in% 3:6 within mutate

library(dplyr)
df %>% 
  mutate(a = ifelse(id %in% 3:6 & is.na(a), 
      "Transportation Element Maps 2012", a))
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