Search code examples
rweekday

Is there a R function to find the next position of an element in a list


I want to create a function that returns the next day

Here is what I got:

next_day <- function(day){
 + week = list('monday','tuesday','wednesday','thursday','friday','saturday','sunday')
 + pos <- index(day, week)
 + if(day=='sunday') return('monday')
 + if match(day,week) return week[pos+1]

Error: unexpected symbol in:
"   + if(day=='sunday') return('monday')
    + if match"

Solution

  • nextday <- function(day){
      week <- list('monday','tuesday','wednesday','thursday','friday','saturday','sunday')
      day <- stringr::str_to_lower(day)
      index <- match(day, week)
      if(index == 7){
        index = 0
      }
      week[[index+1]]
    }
    
    nextday("sunday")
    

    Output :

    [1] "monday"