简体   繁体   English

如何根据模式重命名列名

[英]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.例如,17/18 转换为 2017-2018。 In the full data set, the years go from 00/01 - 98-99 (2098-2099).在完整的数据集中,年份 go 从 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:像这样产生一个 dataframe :

    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" .您可以使用正则表达式来捕获数字并添加前缀"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 "-"您可以在"/" (创建一个列表)上拆分倒数第二个元素,使用paste添加前缀"20"并用"-"折叠

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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