I have a column that is the number of hours slept which was created by subtracting a wake_up column from the went_to_slepp columne - however, I am getting negative numbers because difftime is not recognizing that the PM values are for the first day and AM numbers are for the following day.
I realized that, mathematically, I come out with the correct number of hours if I can add 24 to the negative values.
However, because I have NA values I can only replace the negative values with 0 or NA and am getting an error when I try to add 24.
Example:
df$hours_slept[df$hours_slept < 0] <- d5_df$hours_slept + 24
This gives me the error:
Error in NextMethod("[<-"): NAs are not allowed in subscripted assignments
I tried adding.is.na but that did not work in the way I thought it would
Thanks
You could use ifelse
like so:
set.seed(1234)
df <- data.frame(hours_slept = sample(seq(-12,12, .1),20, replace=TRUE))
df$hours_slept[sample(1:20,8)] <- NA
df
#> hours_slept
#> 1 -9.3
#> 2 -4.1
#> 3 NA
#> 4 NA
#> 5 11.5
#> 6 -1.0
#> 7 1.6
#> 8 NA
#> 9 4.5
#> 10 NA
#> 11 1.1
#> 12 -2.3
#> 13 NA
#> 14 9.3
#> 15 NA
#> 16 -5.1
#> 17 -4.2
#> 18 8.5
#> 19 NA
#> 20 NA
df <- transform(df, hours_slept=ifelse(hours_slept < 0, -hours_slept, hours_slept))
df
#> hours_slept
#> 1 9.3
#> 2 4.1
#> 3 NA
#> 4 NA
#> 5 11.5
#> 6 1.0
#> 7 1.6
#> 8 NA
#> 9 4.5
#> 10 NA
#> 11 1.1
#> 12 2.3
#> 13 NA
#> 14 9.3
#> 15 NA
#> 16 5.1
#> 17 4.2
#> 18 8.5
#> 19 NA
#> 20 NA
Created on 2022-07-26 by the reprex package (v2.0.1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.