Run a function that requires user interaction in a knitr document

前端 未结 1 1484
既然无缘
既然无缘 2021-01-25 02:49

I am using the package Knitr to write a report in latex. I have written the following function in my snippet:

sum <- function(){
  n <- as.numeric(readline         


        
相关标签:
1条回答
  • 2021-01-25 03:31

    To be able to input anything interactively, readline() has to be used in an interactive R session, but your Rnw document is compiled in a non-interactive R session (why?)---this is only my guess, since you didn't mention how you compiled the document, and most people probably click the "Knit" button in RStudio, which means the document is compiled in a separate non-interactive R session.

    In a non-interactive R session, readline() doesn't allow interactive input, and returns "" immediately, which leads to the error you saw:

    > 1:""
    Error in 1:"" : NA/NaN argument
    

    If you have any code that requires human interaction (such as inputting numbers), the document has to be compiled in an interactive R session, and the way to do it is to run knitr::knit('your-document.Rnw') in the R console. (For R Markdown users, run rmarkdown::render() instead.)

    That said, I don't recommend putting code that requires interaction in a knitr document, because it will make it harder to be reproducible (the result depends on interactive input, which is not predictable).

    You may define your function so it doesn't absolutely require human interaction, e.g.,

    sum2 <- function(n = as.numeric(readline("Enter any positive integer"))) {
      i <- 1:n; s <- sum(i)
      return(s)
    }
    

    Then if you want to call the function in a non-interactive R session, you can pass a value to the argument n, e.g.,

    sum2(10)
    
    0 讨论(0)
提交回复
热议问题