Output a boolean from an Rscript into a Bash variable
bash, r
Solution
Instead of using either print() or the implicit print()-ing that occurs when an object name is offered to the R interpreter, you should be using `cat()` which will not prepend the "[1] " in front of either TRUE or FALSE. If you want 0/1, then use `cat(as.numeric(.))`. Try this instead:
myinput <- TRUE #or FALSE
FunctionName <- function(test){
if (test == TRUE){
val <- TRUE
} else {
val <- FALSE
}
cat(as.numeric(val))
}
FunctionName(myinput)
If you needed that value for further processing you could also use this:
cat(as.numeric(val)); invisible(val)
Problem
I have an R script that outputs TRUE or FALSE. In R, it's using a bona fide T/F data type, but when I echo its return value to bash, it seems to be a string, saying: `"[1] TRUE"` or `"[1] FALSE"` They are both preceded by [1]. Neither is [0], that is not a typo. Anyway, the result of this is what when I try to test on the output of this Rscript to run a subsequent script, I have to do string comparison to "[1] TRUE" as below, instead of comparing to "TRUE" or "1" which feels cleaner and better. ``` A=$(Rscript ~/MyR.r) echo $A if [ "$A" == "[1] TRUE" ]; then bash SecondScript.sh fi ``` How can I make R either output a true Boolean, or Bash accept the output string and convert it to 0/1 for comparison? That is, I'd rather test for... ``` if [ $A == TRUE ]; ``` than ``` if [ "$A" == "[1] TRUE" ]; ``` Is that possible, or should I be happy with this, how it is, which works? *** UPDATE *** Here's the minimalized version of the Rscript that generates this... ``` myinput <- TRUE #or FALSE FunctionName <- function(test){ if (test == TRUE){ val <- TRUE } else { val <- FALSE } return(val) } FunctionName(myinput) ```