Code is running but Knit to HTML does not work

My code is running and I can see the output but when i'm trying to knit to HTML i get this error message.

table_1 <-data.frame(table(my_df$a))

freq <- (table_1[,2])
years <- (table_1[,1])

ggplot(data=table_1, aes(x=years,y=freq))+
  geom_bar(stat = "identity", fill="palevioletred1",color="violetred", width =0.97)

Hi,

Some things to check when knitting fails, but the code runs manually:

  • Are all package libraries specified in the markdown code (sometimes you activated them before, outside the code but during knitr it needs to reload them)
  • Are there any variables in the current environment that are not created in the code (same issue as with libraries as markdown cannot access environment variables outside the code). Clear the environment in R-Studio (removing all variables) and see if you can still run code manually.
  • Are you loading any external data? Check if the paths are correct, as knitr does not use the working directory but the root of the project (or R)

If non help, please create a minimal reproducible example

Hope this helps,
PJ

3 Likes

This is my code:

mc_s_f <- function(N,s,f){
  s <- c()
  f <- c()
  for (i in 1:N){
    samp_s <- sample(s,1)
    samp_f <- sample(f,1)
    f_samp <- c(f_samp, samp_f)
    if (samp_s>samp_f){
      s<- c(s,1)}
    }
  s_prob <- sum(s)/N
  return(s_prob)
}

The function is running and i can see output.

This is the error I get when I try to knit to HTML:

Hi,

Your function is not working properly when I test it:

  • the s and f variable in the first part of the function are assigned an empty vector: This will result in error when trying to acces them in the for loop. It seems you want to use the s and f from the input of the function(?), but at the moment you're overwriting the values with empty vectors. If you want to convert the values to vectors use as.vector()
  • The vector f_samp is never defined in your function and then suddenly used in the for-loop, this will lead to errors. Define it before the for-loopstarts (empty)

PJ

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.