将Rscript中的布尔值输出到Bash变量中 [英] Output a boolean from an Rscript into a Bash variable
问题描述
我有一个输出TRUE或FALSE的R脚本.在R中,它使用的是真正的T/F数据类型,但是当我将其返回值回显给bash时,它似乎是一个字符串,说:
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]是"
或
"[1]错误"
它们都以[1]开头.[0]都不是,不是错字.无论如何,当我尝试在此Rscript的输出上测试以运行后续脚本时,其结果是什么,我必须将字符串与"[1] TRUE"进行如下字符串比较,而不是与"TRUE"或"1",感觉更干净,更好.
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
如何使R输出真实的布尔值,或者Bash接受输出字符串并将其转换为0/1进行比较?也就是说,我宁愿测试...
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 ];
比
if [ "$A" == "[1] TRUE" ];
这是可行的,还是应该让我满意?
Is that possible, or should I be happy with this, how it is, which works?
*更新*
这是生成此脚本的Rscript的最小化版本.
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)
推荐答案
您应该使用 cat()
不会在"TRUE"或"FALSE"前面加上"[1]".如果您想要0/1,则使用 cat(as.numeric(.))
.尝试以下方法:
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)
这篇关于将Rscript中的布尔值输出到Bash变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!