Muhammad Kamil
Muhammad Kamil

Reputation: 665

How to replace NA with a string based on a condition in R?

I have the following data:

name <- c(NA, NA)
code <- c("KSV", "KSV")
testing_data <- cbind.data.frame(name, code) 

For all code == "KSV", I want to replace the NA with "Kosovo". Any help would be appreciated.

Upvotes: 2

Views: 1692

Answers (3)

GuedesBF
GuedesBF

Reputation: 9858

You can use ifelse() and replace_na()

library(tidyr)
library(dplyr)

testing_data %>% mutate(name=ifelse(code=='KSV', replace_na(name, 'Kosovo'), name))

Slightly simpler version with case_when():

testing_data %>% mutate(name=case_when(code=='KSV' ~replace_na(name, 'Kosovo')))

Upvotes: 3

Anoushiravan R
Anoushiravan R

Reputation: 21908

You can use the following code:

library(dplyr)

testing_data %>%
  mutate(name = ifelse(is.na(name) & code == "KSV", "Kosovo", name))

    name code
1 Kosovo  KSV
2 Kosovo  KSV

or as an alternative with case_when:

testing_data %>%
  mutate(name = case_when(
    is.na(name) & code == "KSV" ~ "Kosovo",
    TRUE ~ as.character(name)
  ))

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101209

A base R option using replace

transform(
  testing_data,
  name = replace(name,code == "KSV" & is.na(name),"Kosovo")
)

or ifelse

transform(
  testing_data,
  name = ifelse(code == "KSV" & is.na(name), "Kosovo",name)
)

gives

    name code
1 Kosovo  KSV
2 Kosovo  KSV

Upvotes: 2

Related Questions