ZachW
ZachW

Reputation: 19

Replacing NAs in a time variable in R

I am having issues when dealing with the NAs in my dataframe.

The variable that has all the NAs is a time variable in the format HMS. I want to replace the NAs with 00:00:00.

Here is an example of what I am looking at.

< time> 00:00:07, 00:00:02, NA, 00:00:00, NA, 00:00:00, 00:00:00, NA, 00:00:00

Or a better view might be

glimpse(k$hold_time)
'hms' num [1:965201] 00:00:07 00:00:02 NA 00:00:00 ...
   - attr(*, "units")= chr "secs"

I have tried to run the following code but it returns the same data with no changes.

K$hold_time[is.na(k$hold_time)] <- 0

Also when I run this line it gives me the correct amount of NAs so I know that R is picking them up correctly.

sum(is.na(k$hold_time))

Upvotes: 0

Views: 72

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

It looks like hold_time is of class hms. Try using :

k$hold_time[is.na(k$hold_time)] <- hms::hms(0)

Reproducible example :

set.seed(123)
k <- data.frame(hold_time = hms::hms(sample(100, 10)))
k$hold_time[c(5, 8)] <- NA
k

#   hold_time
#1   00:00:31
#2   00:01:19
#3   00:00:51
#4   00:00:14
#5         NA
#6   00:00:42
#7   00:00:50
#8         NA
#9   00:01:37
#10  00:00:25


k$hold_time[is.na(k$hold_time)] <- hms::hms(0)
k
#   hold_time
#1   00:00:31
#2   00:01:19
#3   00:00:51
#4   00:00:14
#5   00:00:00
#6   00:00:42
#7   00:00:50
#8   00:00:00
#9   00:01:37
#10  00:00:25

Upvotes: 1

Related Questions