简体   繁体   中英

Convert column of time (as character decimals from Excel) to time in R

I'm trying to convert a column of time (which I imported from Excel) that R has converted into a decimal/character string back into hh:mm:ss time. I have seen many good answers (using library chron, for example), but I keep getting these errors:

 My data:
 > head(env$Time, 10)
     [1] "0.41736111111111113" "0.6020833333333333"  "0.45"                "0.47222222222222227" "0.5131944444444444" 
     [6] "0.51250000000000007" "0.47361111111111115" "0.44791666666666669" "0.35138888888888892" "0.45277777777777778"

    times(env$Time)
        Error in convert.times(times., fmt) : format h:m:s may be incorrect
        In addition: Warning message:
        In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
          8173 entries set to NA due to wrong number of fields
        
    chron(times(env$Time))
        Error in convert.times(times., fmt) : format h:m:s may be incorrect
        In addition: Warning message:
        In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
          8173 entries set to NA due to wrong number of fields
        
    strptime(env$Time, format = "%H:%M:%S")
        [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
        [38] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Found this answer here: How to express a decimal time in HH:MM

x <- as.numeric(env$Time) # Store time variable as numeric vector
env$Time2 <- sub(":00$", "", round(times(x), "min")) # Run this code to save as new column in dataframe (note, don't need to divide by 24 if decimal is fraction of a day like my data is

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM