0

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.

tashu
  • 11
  • 5

2 Answers2

1

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)
marbel
  • 7,560
  • 6
  • 49
  • 68
  • Hello, Thank you so much. Can I ask you why did you use nchar here ? because I did exactly the same without nchar and it was not working. – tashu Oct 01 '20 at 08:00
  • I use `nchar` because it counts the number of characters. Use `dput` to post your data – marbel Oct 01 '20 at 15:52
0

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)
Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27
  • Hi Daniel, Thanks for your comment but it is not working. Previously I had blanks but now it is showing me "NA" using your code and replacing it with NA. nothing happens. – tashu Oct 01 '20 at 08:04
  • ```head(data$`Direct to Test?`) [1] "Yes" "Yes" "Yes" NA "Yes" "Yes" ``` – tashu Oct 01 '20 at 08:05