Ifelse with mutiple actions

I am looking for a way to do multiple actions, if the condition is false:

eg:

ifelse(file.exists(cool_dataset.csv),
df <- read_csv(cool_dataset.csv),
shell.exec(run_batchfile.bat) "then" Sys.sleep(60) "then" df <- read_csv(cool_dataset.csv))

I can't figure out, how to replace "then" with the correct syntax.

Any help appreciated.

Firstly I should make the obligatory plea to pose your question as a reproducible example (Check out FAQ: What's a reproducible example (`reprex`) and how do I do one? for details).

In the case when I need my ifelse to have complex logic, this sounds like the switch.
https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/switch

it looks like you might try trycatch as I think you are testing if a file exists, and if not you are waiting a minute.

code below not tested.. so consider it pseudocode

mydat <- "cool_dataset.csv"

openMyData <- function(datfile) <- {
tryCatch(read_csv(datfile) , 
  error=function(e) Sys.sleep(60); openMyData(datfile)
}

openMyData(mydat)

I second @jdlong's suggestion to take a look at tryCatch for your specific case, but to answer the question more generally:

You seem to be looking for a branching flow control structure. In R, that's:

if (cond) cons.expr  else  alt.expr

(See: https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/Control).

For your code:

if (file.exists(cool_dataset.csv)) {
  df <- read_csv(cool_dataset.csv)
} else {
  shell.exec(run_batchfile.bat)
  Sys.sleep(60)
  df <- read_csv(cool_dataset.csv)
}

Brackets are necessary for the multi-line style I used here, and in single-line style when you have more than one expression in a branch. Style guides (including the tidyverse style guide) often recommend defaulting to using brackets and multiple lines, and only using a single-line, no-bracket style if your statement is very simple.

ifelse is a function for conditional selection of elements. Roughly speaking, it returns a new object that is meant to have all the properties of the one you tested, except with element values chosen based on the outcome of the test. The dplyr version, if_else, is more strict about data types, and therefore has more predictable output.

6 Likes

Thank you @jcblum for the generall solution. This is exactly, what I was looking for.

I did try the approach with tryCatch, but I prefere the solution with if ... else because of readability.