-3

I need to cleansing the data that contain the value of '' (a null value of string). There are two things I will do next: 1. Counting the number of null string value. 2. Replacing them with NA value

However, there are some problem to accomplish the work. I tried using the sapply function with the function of isBlank (identifying the null srting value). It doesn't return the value of TRUE/FALSE for each element but for each column. Thus I can't use the colSums function to do the job.

I'm not sure if it could be the string manipulation function as a parameter to sapply, could anyone help me with it?

isBlank=function(x){
  if(!is.na(x) && x==''){
    return(TRUE)
  }else{
    return(FALSE)             
  }   
}

sapply(train,isBlank)
Bellerofont
  • 1,081
  • 18
  • 17
  • 16
jun wu
  • 1
  • 1
  • You need `&` instead of `&&`. We can do this easily with `!is.na(train) & train==""` – akrun Mar 27 '17 at 08:52
  • Your way is absolutely suitable for this case , Nevertheless I just wondering why the sapply doens't work with the function of isBlank. Anyway, I'm appreciated for your great help! – jun wu Mar 27 '17 at 12:20
  • It wont work because You are `return`ing a single TRUE/FALSE per each column instead of each element – akrun Mar 27 '17 at 12:23
  • Could it be possible to use the
     sapply function that  returning each element
    – jun wu Mar 27 '17 at 12:37

1 Answers1

0

If it is a data.frame, we can do this without looping by converting to logical matrix

i1 <- !is.na(train) & train==""

and then replace the blanks ("") to NA

replace(train, i1, NA)

data

set.seed(24)
train <- as.data.frame(matrix(sample(c(NA, "", 1:5), 5*5, 
           replace=TRUE), ncol=5), stringsAsFactors=FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you for the understandable illustration. Got it totally. – jun wu Mar 27 '17 at 12:23
  • Although I'v been using stackoverflow to solve many R questions, I'm still new to the forum. I was trying to finish the question but can't find the botton,lol. – jun wu Mar 27 '17 at 12:40