[英]Replacing NAs in a time variable in R
I am having issues when dealing with the NAs in my dataframe.我在处理 dataframe 中的 NA 时遇到问题。
The variable that has all the NAs is a time variable in the format HMS.具有所有 NA 的变量是 HMS 格式的时间变量。 I want to replace the NAs with 00:00:00.我想用 00:00:00 替换 NA。
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.此外,当我运行这条线时,它给了我正确数量的 NA,所以我知道 R 正确地拾取它们。
sum(is.na(k$hold_time))
It looks like hold_time
is of class hms
.看起来hold_time
是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.