I am having problem in running functions in R. Whenever I want to run them I always get the message that the function/object is not available. though I saved it in the working directory. For it to run, I have to paste it in the R window. Any idea on what I am missing highly appreciated.
2 Answers
Use the source function to read the file.
If you do this a lot, I recommend the package devtools, or RStudio. Or both.
3 Comments
Matthew Lundberg
I don't understand what you're asking. That is not a function (not that it makes any difference, files can contain more than just functions).
abraham
Sorry, I created a function just as normal f<-function(x=4){....} and saved it in my setwd. However when I try to call it f() or f(4) the tells me that the object is not available. but when I paste all the function on the R window and call it then it works.
Jason Morgan
Saving the function definition as a file does not evaluate (define) it. As Matthew says, you need to use
source to evaluate the function and bring it into the namespace. When you paste the function into the REPL, that's what's happening. In other words, if you save the function in a file my-function.R, you can then have R evaluate it by source("./my-function.R").So as exposed above, there are several steps to follow. It won't work if one of them is missing :-)
1) Set your source folder
setwd("///.../admin/Documents")
2) Create your function and save it:
fun = function(...){
your function
}
dump("fun", file = "Code_fun.R")
3) Call your function
source("Code_fun.R")
Then you can go ahead
fun(3) = ...