Reputation: 15
I am trying to convert a column from Factor to numeric so I can then run statistical summary (mean, median, max, min). However I keep getting NA when running any of the statistics for this column.
Before running any conversion code, if I run str()
,
the type is 'hms' num [1:5860776] 00:40:56 01:08:32 00:07:19......
I tried the following code
all_trips$ride_length <- as.numeric(as.character(all_trips$ride_length))
and is.numeric(all_trips$ride_length)
reads TRUE
when I then run str()
I get
num [1:5860776] NA NA NA NA NA NA NA ....
Any help is appreciated.
Upvotes: 1
Views: 45
Reputation: 887058
The as.character
converts to character
class from hms
(where the storage mode is numeric
),
> mode(hms::as_hms("12:34:56"))
[1] "numeric"
> typeof(hms::as_hms("12:34:56"))
[1] "double"
> class(hms::as_hms("12:34:56"))
[1] "hms" "difftime"
and thus when we coerce to numeric with as.numeric
from as.character
, it returns NA as there are characters (:
)
library(magrittr)
hms::as_hms("12:34:56") %>%
as.character %>%
as.numeric
[1] NA
hms::as_hms("12:34:56") %>%
as.numeric
[1] 45296
Upvotes: 1