0

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 2

3

Use the source function to read the file.

If you do this a lot, I recommend the package devtools, or RStudio. Or both.

Sign up to request clarification or add additional context in comments.

3 Comments

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).
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.
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").
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.