R语言中转换非常规时间格式3:34'35"为数值类型的方法问询
Got it, let's work through this problem—those apostrophes and quotes in your time string definitely throw R off when importing as a factor. Here are a few straightforward, reliable methods to convert it into either a proper time object or a numeric value (like total seconds):
Method 1: Use lubridate for Clean Time Objects
This is my go-to for time handling because it's intuitive and requires minimal string manipulation:
- First, convert your factor column to a character vector (since factor operations can be tricky):
time_char <- as.character(your_data$time_column) - Clean up the weird symbols: replace the single apostrophe with a colon, and strip out the double quote:
clean_time <- gsub("'", ":", gsub('"', "", time_char)) # Now your strings look like "3:34:35" - Use
lubridate::hms()to parse it into a time period object (this works for hours:minutes:seconds):library(lubridate) time_period <- hms(clean_time)- The
time_periodobject is aPeriodtype, which lets you do time arithmetic directly (e.g., adding/subtracting times). - If you want a numeric value (total seconds), just convert it:
time_seconds <- as.numeric(time_period)
- The
Method 2: No External Packages (Base R Only)
If you don't want to install extra libraries, you can split the string components manually and calculate total seconds:
- Convert to character and split the string into hours, minutes, and seconds parts:
time_str <- as.character(your_data$time_column) # Split on colon and apostrophe to get separate components parts <- strsplit(time_str, split = "[:']") - Extract each component, clean the seconds (remove the double quote), and convert to numeric:
hours <- sapply(parts, function(x) as.numeric(x[1])) minutes <- sapply(parts, function(x) as.numeric(x[2])) seconds <- sapply(parts, function(x) as.numeric(gsub('"', "", x[3]))) - Calculate total seconds (or convert to other units if needed):
total_seconds <- hours * 3600 + minutes * 60 + seconds
Method 3: Use readr for Direct Parsing
The readr package has a flexible parse_time() function that can handle custom formats directly, no need for extra string cleanup:
library(readr) # The format string matches your original pattern: %H (hours), %M (minutes), literal ', %S (seconds), literal " time_obj <- parse_time(as.character(your_data$time_column), format = "%H:%M'%S\"")
- This returns a
POSIXct-like time object, which integrates well with other R time functions. - Again, convert to numeric seconds with
as.numeric(time_obj)if needed.
Quick Note on Edge Cases
If you have missing values or malformed entries (e.g., strings that don't follow the h:m's" pattern), wrap the parsing functions in tryCatch() or use na_if() to handle them gracefully. For example:
clean_time <- gsub("'", ":", gsub('"', "", time_char)) clean_time[clean_time == ""] <- NA time_period <- hms(clean_time)
内容的提问来源于stack exchange,提问作者Denis

