R using data [data == ""] <- NA

I am working with a dataset that has all kinds of column classes, including the Date class. I am trying to assign NA to all empty values ​​in this dataset as follows:

data[data==""] <- NA

Obviously, there are some problems in the date column because the following error occurs:

Error in charToDate(x) : 
character string is not in a standard unambiguous format

I really don’t know why this error occurs, since there are no empty values ​​in the date column, so nothing should be there. The dates in the date column are in the standard format "% Y-% m-% d".

What is the problem and how can I solve it?

+4
source share
1 answer

, "", '' NA

 indx <- sapply(data, class)!='Date'
 data[indx][data[indx]==''] <- NA

"", . - matrix, character.

 data[as.matrix(data)==''] <- NA

@Frank ( replace)

 data[indx] <- lapply(data[indx],  function(x) replace(x, which(x==''), NA))

 set.seed(49)
 data <- data.frame(Col1= sample(c('',LETTERS[1:3]), 10, replace=TRUE), 
      Col2=sample(c('',LETTERS[1:2]), 10, replace=TRUE), 
      Date=seq(as.Date('2010-01-01'),length.out=10, by='day'),
       stringsAsFactors=FALSE)
+2

All Articles