0

This might be a simple question but I have tried a few things and they're not working. I have a large data frame with date/time formats in. An example of my data frame is:

  Index       FixTime1                  FixTime2
    1     2017-05-06 10:11:03               NA
    2            NA              2017-05-07 11:03:03

I want to remove all NAs from the dataframe and make them "" (blank). I have tried:

df[is.na(df)]<-"" 

but this gives the error:

Error in as.POSIXlt.character(value) : 
character string is not in a standard unambiguous format

Again, this is probably very simple to fix but can't find how to do this, while keeping each of these columns in time/date format

4
  • 1
    You have a POSIXlt cclass. Change it to character class
    – akrun
    Mar 12, 2018 at 13:04
  • 2
    You would have to convert all your dates to characters to do that. What is wrong with having NAs?
    – James
    Mar 12, 2018 at 13:06
  • I can't have NAs as I'm doing an if statement in a loop after and it breaks because of the NA
    – Fiona
    Mar 12, 2018 at 13:07
  • 1
    You can use & !is.na( to avoid that
    – akrun
    Mar 12, 2018 at 13:08

2 Answers 2

1

We can use replace

df[] <- replace(as.matrix(df), is.na(df), "")
df
#   Index            FixTime1            FixTime2
#1     1 2017-05-06 10:11:03                    
#2     2                     2017-05-07 11:03:03
1

Here a possible solution on a toy dataset, adapt this code to your needs:

df<-data.frame(date=c("01/01/2017",NA,"01/02/2017"))
df
        date
1 01/01/2017
2       <NA>
3 01/02/2017

From factor to character, and then remove NA

 df$date <- as.character(df$date)
 df[is.na(df$date),]<-""
 df
            date
    1 01/01/2017
    2           
    3 01/02/2017

In your specific example, this could be fine:

df_2<-data.frame(Index=c(1,2),
+                FixTime1=c("2017-05-06 10:11:03",NA),
+                FixTime2=c(NA,"2017-05-07 11:03:03"))


df_2<-data.frame(lapply(df_2, as.character), stringsAsFactors=FALSE)

df_2[is.na(df_2$FixTime1),"FixTime1"]<-"" 
df_2[is.na(df_2$FixTime2),"FixTime2"]<-""
df_2
  Index            FixTime1            FixTime2
1     1 2017-05-06 10:11:03                    
2     2                     2017-05-07 11:03:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.