简体   繁体   中英

How to rename column names based on pattern

I'm needing to reformat the year columns according to a pattern. For example, 17/18 transformed to 2017-2018. In the full data set, the years go from 00/01 - 98-99 (2098-2099).

Here is the code to create a sample dataset:

id <- c(500,600,700)
a <- c(1,4,5)
b <- c(6,4,3)
c <- c(4,3,4)
d <- c(3,5,6)
test <- data.frame(id,a,b,c,d)
names(test) <- c("id","17/18","18/19","19/20","20/21")

Produces a dataframe like so:

    id  17/18 18/19 19/20 20/21
500 1     6     4     3
600 4     4     3     5
700 5     3     4     6

Desired outcome:

id  2017-2018 2018-2019 2019-2020 2020-2021
500 1         6         4         3
600 4         4         3         5
700 5         3         4         6

You can use regex to capture the digits and add prefix "20" .

names(test)[-1] <- sub('(\\d+)/(\\d+)', '20\\1-20\\2', names(test)[-1])

test
#   id 2017-2018 2018-2019 2019-2020 2020-2021
#1 500         1         6         4         3
#2 600         4         4         3         5
#3 700         5         3         4         6

Given this input

x <- c("id","17/18","18/19","19/20","20/21")

You can split the second to last elements on "/" (which creates a list), use paste to add a prefixed "20" and collapse by "-"

x[-1] <- sapply(strsplit(x[-1], "/", fixed = TRUE), paste0, "20", collapse = "-")

Result

x
[1] "id"        "2017-2018" "2018-2019" "2019-2020" "2020-2021"

additional solution

colnames(test)[-1] <- names(test)[-1] %>% 
  strsplit(split = "/") %>% 
  map(~ str_c("20", .x)) %>% 
  map_chr(~str_c(.x, collapse = "-"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM