【问题标题】:How to rename column names based on pattern如何根据模式重命名列名
【发布时间】:2020-09-29 15:01:55
【问题描述】:

我需要根据模式重新格式化年份列。例如,17/18 转换为 2017-2018。在完整的数据集中,年份从 00/01 - 98-99 (2098-2099)。

这是创建示例数据集的代码:

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

像这样生成一个数据框:

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

期望的结果:

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

【问题讨论】:

    标签: r string replace


    【解决方案1】:

    您可以使用正则表达式捕获数字并添加前缀"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
    

    【讨论】:

      【解决方案2】:

      给定这个输入

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

      您可以拆分"/" 上的倒数第二个元素(创建一个列表),使用paste 添加前缀"20" 并折叠"-"

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

      结果

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

      【讨论】:

        【解决方案3】:

        其他解决方案

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-10-15
          • 1970-01-01
          • 2020-07-05
          • 2022-01-07
          • 2020-10-12
          • 1970-01-01
          • 2021-05-17
          • 2015-08-10
          相关资源
          最近更新 更多