executing an r script with bash
Here’s a tangent:
Let’s say you need to randomly generate a series of practice exam questions. You have a bunch of homework assignments, lab questions and midterms, all of which are numbered in a standard way so that you can sample from them.
Here’s a simple R script to run those samples and generate a practice exam that consists of references to the assignments and their original numbers.
## exam prep script
## build hw data
j <- 1
hw <- data.frame(hw_set = NA, problm = seq(1:17))
for (i in seq(1:12)) {
hw[j,1] <- paste0("hw",j)
j <- j+1
}
library(tidyr)
hw <- expand(hw)
names(hw) <- c("problm_set", "problm")
## build exam data
j <- 1
exam <- data.frame(exam_num = NA, problm = seq(1:22))
for (i in seq(1:8)) {
exam[j,1] <- paste0("exam",j)
j <- j+1
}
library(tidyr)
exam <- expand(exam)
names(exam) <- c("problm_set", "problm")
## create practice exam
prctce <- rbind(exam,hw)
prctce_test <- prctce[sample(1:nrow(prctce), size=22),]
row.names(prctce_test) <- 1:nrow(prctce_test)
print(prctce_test)
As the last line indicates, the final step of the script is to output a prctce_test … that will be randomly generated each time the script is run, but may include duplicates over time.
Sure. Fine. Whatever.
Probably a way to do this with Drupal … or with Excel … or with a pencil and paper … why use R?
Two reasons: 1) using R to learn R and 2) scripting this simulation let’s you automate things a little bit easier.
In particular, you can use something like BASH to execute the script n number of times.
for n in {1..10}; do Rscript examprep.R > "YOUR_PATH_HERE/practice${n}.txt"; done
That will give you 10 practice test txt files that are all named with a tokenized number, with just one command. And of course that could be written into a shell script that’s automated or processed on a scheduler.
Sure. Fine. Whatever.
OK. While this is indeed a fairly underwhelming example, the potential here is kind of interesting. Our next step is to investigate using Drupal Rules to initiate a BASH script that in turn executes an algorithm written in R. The plan is to also use Drupal as the UI for entering the data to be processed in the R script.
Will document that here if/when that project comes together.