以下向量是示例数据框中列名的向量:
x <- c("Col1", "Blah", paste0("M", seq(from = 1, to = 24)), "Ma", "Mam", "Mel", "Stuff")
我想将列名M1
,M2
,...,M12
替换为January
,February
,...,{ {1}}。理想情况下,我希望我的解决方案是
December
我知道
x[some expression] <- month.name
但我怎样才能匹配> x[grep("M[1-9]$", x)]
[1] "M1" "M2" "M3" "M4" "M5" "M6" "M7" "M8" "M9"
,"M10"
和"M11"
?请注意,"M12"
到"M13"
应不匹配。
答案 0 :(得分:1)
您可以使用包stringi
直接替换以下列号。
library(stringi)
stri_replace_all_regex(x, paste0("\\bM", 1:12, "\\b"), month.name, vectorize_all = FALSE)
# [1] "Col1" "Blah" "January" "February" "March" "April"
# [7] "May" "June" "July" "August" "September" "October"
# [13] "November" "December" "M13" "M14" "M15" "M16"
# [19] "M17" "M18" "M19" "M20" "M21" "M22"
# [25] "M23" "M24" "Ma" "Mam" "Mel" "Stuff"