Reputation: 634
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
Upvotes: 1
Views: 487
Reputation: 8880
additional solution
colnames(test)[-1] <- names(test)[-1] %>%
strsplit(split = "/") %>%
map(~ str_c("20", .x)) %>%
map_chr(~str_c(.x, collapse = "-"))
Upvotes: 0
Reputation: 389325
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
Upvotes: 3
Reputation: 26373
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"
Upvotes: 0