假設我有一系列的年周:
s <- c('2020 WK 01', '2021 WK 41', '2021 WK 42', '2021 WK 43', '2021 WK 45')
我想在一個情節標題中向用戶顯示這個,但結果標題太長了。我的想法是將相鄰的年周連字符,例如我期望的結果:
title <- "2020 WK 01, 2021 WK 41 - 43, 2021 WK 45"
在 R 中有沒有一種慣用的方法來做到這一點?
uj5u.com熱心網友回復:
這是一個基本的 R 選項 -
#Get the week number
week_number <- as.numeric(sub('.*WK\\s ', '', s))
#If the weeks are consecutive group them in one
#get the week number from last value and paste it to first value.
unname(tapply(s, cumsum(c(TRUE, diff(week_number) > 1)), function(x) {
if(length(x) > 1) paste(x[1], sub('.*WK\\s ', '', x[length(x)]), sep = '-')
else x
}))
#[1] "2020 WK 01" "2021 WK 41-43" "2021 WK 45"
上面的代碼適用于同年資料,但如果輸入跨越多年,因為它不考慮年份值,則回傳不正確的輸出。我們可以擴展相同的邏輯,包括year值。我使用過 tidyverse圖書館,因為它很容易使用。
library(dplyr)
library(tidyr)
s = c('2020 WK 40', '2021 WK 41', '2021 WK 42', '2021 WK 43', '2022 WK 44')
tibble(s) %>%
separate(s, c('YEAR', 'WEEK_NUM'), sep = '\\s*WK\\s*',
convert = TRUE, remove = FALSE) %>%
arrange(YEAR, WEEK_NUM) %>%
group_by(YEAR, group = cumsum(c(TRUE, diff(WEEK_NUM) > 1))) %>%
summarise(title = if(n() > 1) paste(first(s), last(WEEK_NUM), sep = '-') else s) %>%
pull(title)
#[1] "2020 WK 40" "2021 WK 41-43" "2022 WK 44"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338787.html
標籤:r
上一篇:通過部分匹配洗掉/覆寫行
