How to assign NA to "NO"

161 Views Asked by At

In my dataset I have one column where I need to replace blanks to "No", How can I do this?

The column is a character variable and had only two values, yes and no.

data<- as.data.frame(Upper_GI_2ww)
data$`Direct to Test?` = ifelse(nchar(data$`Direct to Test?`) == "NA", "No",data$`Direct to Test? )

output:

head(data$`Direct to Test?`)
[1] "Yes" "Yes" "Yes" NA    "Yes" "Yes"

Soultion:

It is working fine now, Here is what i did:

First I have converted char to factor.

I used a simple is.na function

data$`Direct to Test?`[is.na(data$`Direct to Test?`)] <-"No"
head(data$`Direct to Test?`)
Yes Yes Yes No  Yes Yes
Levels: No Yes

it is working fine now.

2

There are 2 best solutions below

2
On

You can use nchar to count the number of characters.

df$var = ifelse(nchar(df$var) == 0, "No", df$var)

This is also valid if all you need is to replace "":

df$var = ifelse(df$var == "", "No", df$var)
2
On

Here is a way you can do it with using the sub() function to replace empty strings

#create data
data <- c("", "yes", "", "no")

#make into data.frame
data <- as.data.frame(data)

#replacing empty strings with "No"
sub("^$", "No", data$data)