具有带有姓氏的data.frame
nam <- c("a", paste0("a_", seq(12)))
"a" "a_1" "a_2" "a_3" "a_4" "a_5" "a_6" "a_7" "a_8" "a_9" "a_10" "a_11" "a_12"
如何用数字将名称的数字加1?
预期结果将是
"a" "a_2" "a_3" "a_4" "a_5" "a_6" "a_7" "a_8" "a_9" "a_10" "a_11" "a_12" "a_13"
到目前为止,我的解决方案看起来非常复杂...有没有比这更简单的方法
increment_names <- function(nam){
where <- regexpr("\\d", nam)
ind <- which(where > 0)
increment <- as.numeric(substring(nam[ind], where[ind])) + 1
substring(nam[ind], where[ind]) <- as.character(increment)
nam
}
> increment_names(nam)
[1] "a" "a_2" "a_3" "a_4" "a_5" "a_6" "a_7" "a_8" "a_9" "a_10" "a_11" "a_12" "a_13"
最佳答案
基本regmatches
解决方案:
r <- regexpr("\\d+",nam)
regmatches(nam,r) <- as.numeric(regmatches(nam,r))+1
nam
# [1] "a" "a_2" "a_3" "a_4" "a_5" "a_6" "a_7" "a_8" ...