[英]Running and debugging a script and function in R
I am a newbie. 我是新手。 I've an R file ,containing a function with a parameter. 我有一个R文件,包含一个带参数的函数。 I' d like to perform the two following distinct operations: 我想执行以下两个不同的操作:
suppose to have a simple function in an R file 假设在R文件中有一个简单的函数
"exampleSum"<-
function(x,y){
x<-x+1
return(x+y)
}
Could you tell me which are R commands to perform what I asked. 你能告诉我哪些是R命令来执行我的要求。
You have to call debug(<functionName>)
to step through a function. 您必须调用debug(<functionName>)
来逐步执行函数。 The next time you call the function, the so-called browser environment will automatically be opened and list the content of your function. 下次调用该函数时,将自动打开所谓的浏览器环境并列出函数的内容。 You perform one step by pressing Return or with the n
command (next). 按Return键或使用n
命令(下一步)执行一步。 A single step is one block (usually a single line) that will be listed before it's run. 单步是一个块(通常是一行),它将在运行之前列出。 To run the function to its end, press c
(continue). 要将功能运行到最后,请按c
(继续)。 When you're in browser mode, you can use ls()
, str()
, class()
, ... to inspect the objects. 当您处于浏览器模式时,可以使用ls()
, str()
, class()
,...来检查对象。 Your example looks like this: 您的示例如下所示:
> exampleSum <- function(x, y) {
+ x <- x+1
+ return(x+y)
+ }
> debug(exampleSum) # set debug flag
> exampleSum(1, 2) # run function in browser mode
debugging in: exampleSum(1, 2)
debug: {
x <- x + 1
return(x + y)
}
Browse[2]> n # next step
debug: x <- x + 1
Browse[2]> ls() # show objects
[1] "x" "y"
Browse[2]> x # show x
[1] 1
Browse[2]> c # run function to end
exiting from: exampleSum(1, 2)
[1] 4
> undebug(exampleSum) # remove debug flag
The last call to undebug(<functionName>)
removes the debug flag from the function such that it will be run normally the next time it's called. 最后一次调用undebug(<functionName>)
会从函数中删除调试标志,以便下次调用它时它将正常运行。
You first need to load the function into R's workspace (by copy/pasting it to R). 首先需要将函数加载到R的工作区(通过将其复制/粘贴到R)。 Then, you can run it using exampleSum(x = 1, y = 1)
. 然后,您可以使用exampleSum(x = 1, y = 1)
运行它。 You can check that it's there by typing exampleSum
into R console. 您可以通过在R console中键入exampleSum
来检查它是否存在。 You can also run the script file using source()
. 您还可以使用source()
运行脚本文件。 Example of usage would be source("d:/R/my_script.R")
. 使用示例是source("d:/R/my_script.R")
。
I think you would benefit immensely by reading at least An Introduction to R . 我认为至少阅读一本R简介会让你受益匪浅。 There is also a plethora of books available to R beginners that explain the very basics. R初学者也有很多书可以解释这些基础知识。 Equivalent information is available in the aforementioned AI2R and free materials floating around the internet. 上述AI2R中提供了等效信息,互联网上有免费资料。 Searching the R help list is also... helpful. 搜索R帮助列表也很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.