2

Hi I have a df as below

 a = c("AP_", "AP_", NA, "AP_", "AP_", "HP_", "AP_", "AP_") 
 b = c(20, 30, 40, 10, 20, 10, NA, 12) 
 c = c("A", "B", "C", "D", "E", "", "G", "H") 
 a_output = c("AP_", "AP_", "", "AP_", "AP_", "HP_", "AP_", "AP_") 

 df = data.frame(a, b, c,a_output)

How to get "a_output" column as a result by converting NA to NULL from "a" column

I have tried with grepl as below

  df$a_output = df[is.na(df$a)] <- "" 

Any modification in above statement Thanks in advance

Andrew Haynes
  • 2,612
  • 2
  • 20
  • 35
sasir
  • 167
  • 10

4 Answers4

3

We need to use is.na

df$a_output <- replace(as.character(df$a), is.na(df$a), "")

Also, if we check the class of 'a' column, it is factor, so either '' should be a level in the factor column

levels(df$a) <- c(levels(df$a), "")
df$a[is.na(df$a)] <- ""

or we convert to character and replace it as in the first method

akrun
  • 874,273
  • 37
  • 540
  • 662
2

Another solution, similar to akrun's replace() answer, can be achieved by using ifelse():

df$a_output <- ifelse(is.na(df$a), "", as.character(df$a))

I don't know how it compares speedwise, but it works:

> df
     a  b c
1  AP_ 20 A
2  AP_ 30 B
3 <NA> 40 C
4  AP_ 10 D
5  AP_ 20 E
6  HP_ 10  
7  AP_ NA G
8  AP_ 12 H

df$a_output <- ifelse(is.na(df$a), "", as.character(df$a))

> df
     a  b c a_output
1  AP_ 20 A      AP_
2  AP_ 30 B      AP_
3 <NA> 40 C         
4  AP_ 10 D      AP_
5  AP_ 20 E      AP_
6  HP_ 10        HP_
7  AP_ NA G      AP_
8  AP_ 12 H      AP_

You can convert it to factor with

df$a_output <- as.factor(df$a_output)

if you need it.

LAP
  • 6,605
  • 2
  • 15
  • 28
1

If you dont want a, c, a_output to be a factor variable, the solution could look like this:

df = data.frame(a, b, c,a_output,stringsAsFactors = F)

df$a_output[is.na(df$a)]  <- ""
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69
1

Yet another solution: Uses two steps, but uses the which() function which I think helps with readability.

a_output<-a

a_output[which(is.na(a_output))]<-""  ## which is na, assign ""
Andrew Haynes
  • 2,612
  • 2
  • 20
  • 35