如何在R语言中为数字插入横杠?含6位日期格式转换示例
Got it, let's tackle these two string manipulation tasks in R. Both are straightforward once you know the right functions to use—here are solutions for each scenario:
If you want to add a hyphen between each individual digit (e.g., 1234 → 1-2-3-4), you can use either base R or the stringr package for cleaner syntax.
Base R approach
Convert the number to a string, split it into individual characters, then paste them back together with hyphens:
# Example input my_number <- 12345 # Split into characters, then collapse with hyphens paste0(strsplit(as.character(my_number), "")[[1]], collapse = "-") # Output: "1-2-3-4-5"
stringr approach
Use str_replace_all to match each character and add a hyphen, then trim the trailing hyphen with str_sub:
library(stringr) str_replace_all(as.character(my_number), "(.)", "\\1-") %>% str_sub(end = -2) # Output: "1-2-3-4-5"
For converting 6-digit strings like 631022 to 63-10-22, regular expressions are your best bet—they let you target specific positions in the string.
Base R with sub
The sub function can match and rearrange groups of digits. Here, we split the 6-digit string into three 2-digit groups, then join them with hyphens:
# Example input six_digit_date <- 631022 sub("(\\d{2})(\\d{2})(\\d{2})", "\\1-\\2-\\3", as.character(six_digit_date)) # Output: "63-10-22"
(\\d{2}): Matches a group of 2 digits\\1-\\2-\\3: Reconstructs the string by inserting hyphens between the three groups
stringr approach
Same logic, but with str_replace for more readable syntax:
str_replace(as.character(six_digit_date), "(..)(..)(..)", "\\1-\\2-\\3") # Output: "63-10-22"
(..)is a shorthand for any two characters (perfect since we're dealing with digits)
This works for vectors too—no need to loop! For example:
date_vec <- c(631022, 990101, 050618) sub("(\\d{2})(\\d{2})(\\d{2})", "\\1-\\2-\\3", as.character(date_vec)) # Output: "63-10-22" "99-01-01" "05-06-18"
内容的提问来源于stack exchange,提问作者KhoiSan

