0

I have a a column in R that is called 'Year Week' that shows yearly data and Week Data. 202101 represents the first week in 2021. However, I am try to format it into '01-2021' or '2021-01 to put it in a time series.

Zane Cantrell
  • 247
  • 3
  • 9
  • I think this can help you: https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object – AlexB Jun 30 '21 at 14:27

3 Answers3

2

You can use the my() function from lubridate. Here's the cheatsheet: https://raw.githubusercontent.com/rstudio/cheatsheets/master/lubridate.pdf

MonJeanJean
  • 2,876
  • 1
  • 4
  • 20
2

1) Base R Assuming the input is numeric as shown below use sprintf as in the code below. No packages are used.

x <- 202101
sprintf("%02d-%d", x %% 100, x %/% 100)
## [1] "01-2021"

2) yearmon Another approach is to convert it to yearmon class and then format it. x is defined above.

library(zoo)

format(as.yearmon(as.character(x), "%Y%m"), "%m-%Y")
## [1] "01-2021"

3) sub Another base approach is

sub("(....)(..)", "\\2-\\1", x)
## [1] "01-2021"

4) read.fwf Yet another base approach is:

with(read.fwf(textConnection(as.character(x)), colClasses = "character", c(4, 2)), 
  paste(V2, V1, sep = "-"))
## [1] "01-2021"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

You can use gsub:

gsub("(\\d{4})(\\d{2})", "\\2-\\1", 202101)
#R> [1] "01-2021"