单击 运行 和 SOURCE 时 R 中的不同输出(Rstudio 中的 运行 和 SOURCE 选项卡有什么区别))

Different outputs in R when clicked RUN and SOURCE(What is the difference between RUN and SOURCE tab in Rstudio))

我刚开始学习 R.I 我正在使用条件语句计算二次方程的根。这是我的代码

a <- readline(prompt= "Enter value of a:")
b <- readline(prompt= "Enter value of b:")
c <- readline(prompt= "Enter value of c:")
a <- as.numeric(a)
b <- as.numeric(b)
c <- as.numeric(c)
D <-(b^2-4*a*c)
if (D>0) {
x_1 <- (-b+sqrt(D))/(2*a)  
x_2 <- (-b-sqrt(D))/(2*a)        
result <- (c(x_1 ,x_2 )) 
result
}else if(D==0){  
x <- rep((-b)/(2*a),2)  
}else if(D<0){
  x_1 <- (-b)/(2*a)+(sqrt(abs(D)))/(2*a)*(1i)  
  x_2 <- (-b)/(2*a)-(sqrt(abs(D)))/(2*a)*(1i)   
  result <- (c(x_1 ,x_2 )) 
  result
}

当我按下 运行(ctrl+A) 时,它显示

4 * a 中的错误:二元运算符的非数字参数

当我按源时,它 运行 是我的代码并要求我输入 a、b、c 的值,当我输入值然后按输入它时 returns 我这个

> a <- readline(prompt= "Enter value of a:")
Enter value of a:3

> b <- readline(prompt= "Enter value of b:")
Enter value of b:5

> c <- readline(prompt= "Enter value of c:")
Enter value of c:3

> a <- as.numeric(a)

> b <- as.numeric(b)

> c <- as.numeric(c)

> D <-(b^2-4*a*c)

> if (D>0){                       #why this came ?
+   x_1 <- (-b+sqrt(D))/(2*a)  
+   x_2 <- (-b-sqrt(D))/(2*a)        
+   result <- (c(x_1 ,x_2 )) 
+   result
+ }else if(D==0){  
+   x < .... [TRUNCATED]           #till here
[1] -0.8333333+0.5527708i -0.8333333-0.5527708i
> 

点击运行和来源有什么区别。为什么我不明白不同的输出

  • run 就像将选定的行复制粘贴到控制台,或者将所有选定的文本(包括换行符等)键入控制台。
  • source 将选定的文本保存到一个文件中,然后 运行 在该文件上执行 source 命令。要确切了解 source 的内容,请参阅其文档 (?source)。

运行 命令通常更简单,但也有一些缺点:发生错误或要求输入时它不会停止。在这种情况下,第一个 readline 要求输入。它接收该输入,即文件中的下一行。

小例子:

a <- readline(prompt = "a: ")
print(a)
print(a)

当 运行 这个 (CRTL-A CRTL-ENTER) 时,我在控制台中看到以下内容:

> a <- readline(prompt = "a: ")
a: print(a)
> print(a)
[1] "print(a)"

如您所见,第二行print(a)用作输入。因此,a 的值为 print(a)