簡體   English   中英

如何根據模式重命名列名

[英]How to rename column names based on pattern

我需要根據模式重新格式化年份列。 例如,17/18 轉換為 2017-2018。 在完整的數據集中,年份 go 從 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")

像這樣產生一個 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

期望的結果:

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

您可以使用正則表達式來捕獲數字並添加前綴"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

鑒於此輸入

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"

額外的解決方案

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