Find the day of a week

前端 未结 7 1727
长情又很酷
长情又很酷 2020-11-22 17:37

Let\'s say that I have a date in R and it\'s formatted as follows.

   date      
2012-02-01 
2012-02-01
2012-02-02

Is there any way in R to

相关标签:
7条回答
  • 2020-11-22 17:41

    Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

    require(lubridate)
    df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)
    

    The result is the days in the interval [0,..,6].

    If you want the interval to be [1,..7], use the following:

    df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)
    

    ... or, alternatively:

    df$day = df$day + 1
    
    0 讨论(0)
  • 2020-11-22 17:44
    start = as.POSIXct("2017-09-01")
    end = as.POSIXct("2017-09-06")
    
    dat = data.frame(Date = seq.POSIXt(from = start,
                                       to = end,
                                       by = "DSTday"))
    
    # see ?strptime for details of formats you can extract
    
    # day of the week as numeric (Monday is 1)
    dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))
    
    # abbreviated weekday name
    dat$weekday2 = format(dat$Date, format = "%a")
    
    # full weekday name
    dat$weekday3 = format(dat$Date, format = "%A")
    
    dat
    # returns
        Date       weekday1 weekday2  weekday3
    1 2017-09-01        5      Fri    Friday
    2 2017-09-02        6      Sat    Saturday
    3 2017-09-03        7      Sun    Sunday
    4 2017-09-04        1      Mon    Monday
    5 2017-09-05        2      Tue    Tuesday
    6 2017-09-06        3      Wed    Wednesday
    
    0 讨论(0)
  • 2020-11-22 17:48

    Use the lubridate package and function wday:

    library(lubridate)
    df$date <- as.Date(df$date)
    wday(df$date, label=TRUE)
    [1] Wed   Wed   Thurs
    Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
    
    0 讨论(0)
  • 2020-11-22 17:51

    Look up ?strftime:

    %A Full weekday name in the current locale

    df$day = strftime(df$date,'%A')
    
    0 讨论(0)
  • 2020-11-22 17:52

    form comment of JStrahl format(as.Date(df$date),"%w"), we get number of current day : as.numeric(format(as.Date("2016-05-09"),"%w"))

    0 讨论(0)
  • 2020-11-22 17:57
    df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
    df$day <- weekdays(as.Date(df$date))
    df
    ##         date       day
    ## 1 2012-02-01 Wednesday
    ## 2 2012-02-01 Wednesday
    ## 3 2012-02-02  Thursday
    

    Edit: Just to show another way...

    The wday component of a POSIXlt object is the numeric weekday (0-6 starting on Sunday).

    as.POSIXlt(df$date)$wday
    ## [1] 3 3 4
    

    which you could use to subset a character vector of weekday names

    c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
        "Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
    ## [1] "Wednesday" "Wednesday" "Thursday" 
    
    0 讨论(0)
提交回复
热议问题