Home > Software engineering >  NA returned by R while splitting date time group into date and time columns using POSIXct
NA returned by R while splitting date time group into date and time columns using POSIXct

Time:01-22

dataframe heartrate has Id, date time group as character and value as the three variables. Used the code for splitting date time group into separate columns for date and time but getting NA in the time field.

Used the following code

heartrate <- read_csv("../input/fitbit/Fitabase Data 4.12.16-5.12.16/heartrate_seconds_merged.csv")

head(heartrate)

str(heartrate)

glimpse(heartrate)

heartrate$New_date <- as.Date(heartrate$Time)

heartrate$New_time <- as.POSIXct(heartrate$Time, format = '%H:%M:%S')

The resulting dataframe shows NA in the time fields:

**Id             New_time        New_date        Value**
<dbl>            <dttm>          <date>          <dbl>
2022484408       NA              4-12-20            97
2022484408       NA              4-12-20           102
2022484408       NA              4-12-20           105
2022484408       NA              4-12-20           103
2022484408       NA              4-12-20           101
2022484408       NA              4-12-20            95

Can someone guide me to get the time values in HH:MM:SS? Thanks

CodePudding user response:

This might help you to get that to work:

# Create a character vector of dates and times
dates_times <- c("2022-01-01 12:00:00", "2022-02-01 15:30:00", "2022-03-01 08:45:00")
dates_times <- as.POSIXct(dates_times, format = "%Y-%m-%d %H:%M:%S")

print(dates_times)

# "2022-01-01 12:00:00 NZDT" "2022-02-01 15:30:00 NZDT" "2022-03-01 08:45:00 NZDT"

# Use the format function to extract the date and time
date <- format(dates_times, format = "%Y-%m-%d")
time <- format(dates_times, format = "%H:%M:%S")

# Print the result
print(date)

# "2022-01-01" "2022-02-01" "2022-03-01"

print(time)

# "12:00:00" "15:30:00" "08:45:00"
  • Related