2

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"
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • There are many syntax issues: missing round brackets after last `if` and after `return`, then missing closing curly brackets for the function. – zx8754 Jul 12 '21 at 10:05

4 Answers4

2
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"
MonJeanJean
  • 2,876
  • 1
  • 4
  • 20
  • You're welcome. You can add an message error if the index is equal to `NA` inside the function (which means the user did not provide a correct day format) – MonJeanJean Jul 12 '21 at 09:37
1

Here is another way to solve your problem.

next_day <- function(day) {
  days <- c(sunday='monday', monday='tuesday', tuesday='wednesday', 
            wednesday='thursday', thursday='friday', friday='saturday', 
            saturday='sunday')
  unname(days[tolower(day)])
}




# find next day for a single day
next_day("sunday")
[1] "monday"

# find next days for many days
next_day(c("sunday", "monday", "friday"))
[1] "monday"   "tuesday"  "saturday"
1

Using %%:

next_day <- function(day){
  week = c('monday','tuesday','wednesday','thursday','friday','saturday','sunday')
  week[ (match(day, week) %% 7) + 1 ]
}

#testing
next_day("tuesday")
# [1] "wednesday"

next_day("sunday")
# [1] "monday"
zx8754
  • 52,746
  • 12
  • 114
  • 209
1

I would use a closure, that the vector of days need not to be created each time the function is called.

next_day <- (function(week) {
  function(day) {
    week[1 + match(day, week)]
  }
})(weekdays(seq(as.Date("2000-1-1"), by=1, length.out = 8)))


next_day("Sunday")
#[1] "Monday"

next_day(c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
#[1] "Tuesday"   "Wednesday" "Thursday"  "Friday"    "Saturday"  "Sunday"    "Monday"   

In case upper/lower-case matters use in addition during match tolower or toupper.

GKi
  • 37,245
  • 2
  • 26
  • 48