gpt4 book ai didi

regex - 将 data.frame 的 colnames 增加 1

转载 作者:行者123 更新时间:2023-12-02 05:30:06 25 4
gpt4 key购买 nike

有一个带有colnames的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" ...

关于regex - 将 data.frame 的 colnames 增加 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27953360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com