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
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)