Select in R Programming Language

Our example demonstrates how to wait on multiple channel-like operations in R. Although R doesn’t have built-in channels or select statements like some other languages, we can simulate similar behavior using functions and parallel processing.

library(parallel)

main <- function() {
    # For our example we'll select across two operations.
    c1 <- function() {
        Sys.sleep(1)
        return("one")
    }
    
    c2 <- function() {
        Sys.sleep(2)
        return("two")
    }

    # Each function will return a value after some amount
    # of time, to simulate e.g. blocking operations
    # executing in concurrent processes.
    cl <- makeCluster(2)
    
    # We'll use parallel processing to await both of these values
    # simultaneously, printing each one as it arrives.
    for (i in 1:2) {
        result <- parallel::parLapply(cl, list(c1, c2), function(f) f())
        print(paste("received", result[[1]]))
    }
    
    stopCluster(cl)
}

main()

To run the program:

$ Rscript select.R
[1] "received one"
[1] "received two"

We receive the values “one” and then “two” as expected.

Note that the total execution time is only ~2 seconds since both the 1 and 2 second Sys.sleep() calls execute concurrently.

In this R implementation:

  1. We use the parallel library to simulate concurrent operations.
  2. Instead of channels, we use functions that sleep for a certain amount of time before returning a value.
  3. We create a cluster with two workers using makeCluster().
  4. We use parLapply() to execute both functions in parallel and collect their results.
  5. We print the results as they arrive.

While this doesn’t provide the same level of control as Go’s select statement, it demonstrates a way to wait for and react to multiple concurrent operations in R.