Home > front end >  Change weekday name to a specific pattern
Change weekday name to a specific pattern

Time:12-28

I have a database that has a Week column. Weekday names are Sunday, Monday, Tuesday, etc. However, I would like to automatically change this to the following: Week = c("monday day","tuesday day","wednesday day","thursday day","friday day" "saturday","sunday day" ) . In this case below, as my database only has two days of the week, only Monday and Sunday will be changed. How to adjust this?

 Test <- structure(list(date1 = as.Date(c("2021-11-01","2021-11-01","2021-11-01","2021-11-01")),
                       date2 = as.Date(c("2021-10-18","2021-10-18","2021-10-28","2021-10-30")),
                       Week = c("Monday", "monday", "Sunday", "Sunday"),
                       Category = c("FDE", "FDE", "FDE", "FDE"),
                       time = c(4, 6, 6, 3)), class = "data.frame",row.names = c(NA, -4L))

CodePudding user response:

You can use backreference \\1 to refer back to the Week value given and add day to it in sub's replacement clause:

Test$Week <- tolower(sub("^(.*)$", "\\1 day", Test$Week))

Result:

Test 
       date1      date2       Week Category time
1 2021-11-01 2021-10-18 monday day      FDE    4
2 2021-11-01 2021-10-18 monday day      FDE    6
3 2021-11-01 2021-10-28 sunday day      FDE    6
4 2021-11-01 2021-10-30 sunday day      FDE    3

CodePudding user response:

In your case, you want to use the values of Temp$Week and add ' day' to each value. This is easily accomplished by running:

Test$Week <- gsub('y$', 'y day', Test$Week)

> Test$Week
[1] "Monday day" "monday day" "Sunday day" "Sunday day"

If you would like to have all days of the week (i.e. length(Test$Week) would equal 7), then the following should work:

temp <- c(paste0('2021-12-', 27:31), '2022-01-01', '2022-01-02')
Test$Week <- strftime(temp, '%A')
Test$Week <- gsub('y$', 'y day', Test$Week)

CodePudding user response:

I think you could just use:

library(tidyverse)

Test %>%
   mutate(Week = paste(tolower(Week), "day"))
  •  Tags:  
  • r
  • Related