if loop not runing completely

helo what i want is if interval is less than equal to 24 hrs it should print urgent package if interval is less than equal to 48hrs it should print premium package and greater than 48hrs it should print economy pacakege but every time it is printing urgent package

library(lubridate)
deltime=readline(prompt="Please enter deliery date and time\t") # for input of date and time
T=as.POSIXlt.character(deltime) # to pass the time in formate R accepts
t=Sys.time()
interval=T-t
interval
if(interval<=24){
print(" Urgent Package")
}else if(interval*24<=48){
print("Premium Package")
}else{print("Economy Package")}

what are a couple examples of what you type at the prompt ?

Hi,

Here is my solution

library(lubridate)

#deltime=readline(prompt="Please enter deliery date and time\t") # for input of date and time
deltime="2020-04-18 06:56:47 EDT"

dTime=as.POSIXlt.character(deltime) # to pass the time in formate R accepts
sTime=Sys.time()

interval = interval(sTime, dTime) / hours(1)

if(interval<=24){
  print(" Urgent Package")
}else if(interval<=48){
  print("Premium Package")
}else{print("Economy Package")}

[1] "Economy Package"
  • First of all, it's a bad idea using T as a variable because this is a reserved word and defaults to TRUE (messed up your time difference).
  • I also used the lubridate interval function to calculate the hours difference
  • In the IF-statement, I updated the 48h interval

I don't know what type of input you are expecting from the user, but using a free text type-in to get a full date and time is a guarantee for lots of errors. Either create a simple Shiny app (using date and time inputs) or split your command line input into date and time separately (or even day, month, year and hour of day individually)

Hope this helps,
PJ

1 Like

an alternative to calculating the interval and then dividing by hours(1) would be using the time_length function with unit="hour"

myinterval <- time_length(interval(start = sTime, end = dTime), unit = "hour")

myinterval
1 Like

Hi,

In case you like a function to get a more safe date and time through command-line:

getDeliveryTime = function(){
  deltime=readline(prompt="Please enter delivery year (4 digits):\t") 
  deltime=paste(deltime, readline(prompt="Please enter delivery month (1 - 12 or name):\t"))
  deltime=paste(deltime, readline(prompt="Please enter delivery day (1 - 31):\t"))
  deltime=paste(deltime, readline(prompt="Please enter a delivery hour (0 - 23):\t"))
  return(ymd_h(deltime))
}

deltime = getDeliveryTime()

Of course you could add lots of extra checks in the fuction to see if the values entered are logical and correct.

PJ

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.