Home > Back-end >  Replace NA with text for specific ids
Replace NA with text for specific ids

Time:10-05

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'

CodePudding user response:

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))

CodePudding user response:

You could use the replace function and combine 3:6 and NA together using c as follow:

library(dplyr)

df |> 
  mutate(a = replace(a, id %in% c(3:6, NA), "Transportation Element Maps 2012"))
  • Related