Home > database >  How to change the information in the Week column based on the weekday name given by the system
How to change the information in the Week column based on the weekday name given by the system

Time:04-28

I'm having trouble changing the information in the Week column based on the weekday name given by the system. I do it like this: df1$Week <- weekdays(df1$Week), but it gives an error, how to adjust?

df1 <- structure(
  list(date = c("2021-06-30","2021-06-30","2021-07-02","2021-07-04","2021-07-04","2021-07-09","2021-07-09","2021-07-09"),
       Week= c("Wednesday","Wednesday","Friday","Wednesday","Wednesday","Friday","Friday","Friday")),
  class = "data.frame", row.names = c(NA, -8L))

> df1
        date      Week
1 2021-06-30 Wednesday
2 2021-06-30 Wednesday
3 2021-07-02    Friday
4 2021-07-04 Wednesday
5 2021-07-04 Wednesday
6 2021-07-09    Friday
7 2021-07-09    Friday
8 2021-07-09    Friday


df1$Week <- weekdays(df1$Week)

Error in UseMethod("weekdays") : 
  no applicable method for 'weekdays' applied to an object of class "character"

CodePudding user response:

If you are needing to correct the day of the week due to inaccuracies, then you can convert the date to a date format, then use weekdays to get the correct day of the week. But unsure of your desired output.

library(dplyr)

df1 %>% 
  mutate(date = as.Date(date),
         Week = weekdays(date))

Output

        date      Week
1 2021-06-30 Wednesday
2 2021-06-30 Wednesday
3 2021-07-02    Friday
4 2021-07-04    Sunday
5 2021-07-04    Sunday
6 2021-07-09    Friday
7 2021-07-09    Friday
8 2021-07-09    Friday

CodePudding user response:

Beside the character format of date column also your assignment is df1$Week <- weekdays(df1$Week) wrong:

df1$date <- as.Date(df1$date)
df1$Week <- weekdays(df1$date)
df1
        date     Week
1 2021-06-30 Mittwoch
2 2021-06-30 Mittwoch
3 2021-07-02  Freitag
4 2021-07-04  Sonntag
5 2021-07-04  Sonntag
6 2021-07-09  Freitag
7 2021-07-09  Freitag
8 2021-07-09  Freitag
  •  Tags:  
  • r
  • Related