Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment colnames of a data.frame by 1

Having a data.frame with colnames

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"

How can i increment the numbers of the names with numbers by 1?

The expected Result would be

"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"

So far my solution looks very complicated... Is there an easier way than

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"
like image 827
Rentrop Avatar asked Jun 05 '26 19:06

Rentrop


1 Answers

Base regmatches solution:

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"  ...
like image 67
thelatemail Avatar answered Jun 07 '26 08:06

thelatemail