gpt4 book ai didi

r - 在条件内停止执行脚本

转载 作者:行者123 更新时间:2023-12-05 06:37:31 25 4
gpt4 key购买 nike

我在脚本中有以下代码 test.R :

if (x==2){
stop("the script ends")
}

现在我获取这个脚本

source(test.R)
t <- 2

如果 x==2,我希望代码停止并没有走得更远。但是,它继续并分配 t <- 2 .我可以使用函数 warnings(options)但我想避免使用此选项并在 if 中实现一个条件.有什么建议吗?

最佳答案

您列出的代码应该按预期工作。

举个例子,我做了两个脚本,test.Rtest2.R:

1.文件 test.R:

if (identical(x, 2)) {
stop("the script ends")
}

(注意:我使用 identical(x, 2) 作为检查 x 是否等于 2 的更安全方法,但是 x == 2 在此示例中的工作方式相同。)

2。文件test2.R:

x <- 1
source("test.R")
t <- 1
print("This should be printed.")

x <- 2
source("test.R")
t <- 2
print("This should not be printed!")

现在我从控制台运行 test2.R:

> t <- 5
> source('test2.R')
[1] "This should be printed."
Error in eval(ei, envir) : the script ends
> t
[1] 1

我们看到检查第一次通过,当 x == 1 时,第二次失败,当 x == 2 时。因此,最后的 t 的值为 1,因为第一个分配已运行而第二个未运行。

关于r - 在条件内停止执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com