How to Write Functions in R
1. Open a text editor (for example,
TextPad, Crimson Editor, XEmacs)
2. Write an R function
For example,
square
<-
function(number)
{
answer
<-
number
*
number
return(answer)
}
square
is the name of the function.
function
is the R function that creates functions.
number
is the parameter (name of the value) passed to the square function.
{
delimits the beginning of the function
}
delimits the end of the function
return
is the R function that specifies what the function returns,
in this example,
the value of answer
3. Save the file (by convention with an .R extension). In this
example, the file name is “example.R”.
For this exercise,
we’re going to put in some errors in our function. Color coding is
as follows: red for what the user types;
blue for response by R:
square
<- function(number)
{
answer
<- number * nmber
return(number
}
3. Start R
4. Use the function source
to load your function into your R workspace:
>
source(“example.R”)
Note that the file
name is in quotes and should include either the absolute path, or the
path relative to the location of your R workspace.
5. R will indicate any “syntax” errors at this point and the
line number where they are located. For example,
Error
in parse(file, n, text, prompt) : syntax error on line 5
6. Go back to your text editor and fix the error(s), resave the
file, and reread (source) the function in R.
7. When you get a prompt after “sourcing” your file, then you
can try using the function:
>
square(5)
8. At this point, you may get a
“runtime” error. For example,
Error
in square(5) : Object "nmber" not found
9. Once again, go back to your text editor and fix the error(s),
resave the file, and reread (source) the function in R.
10. The last kind of error you can get, is where the function runs,
but gives the wrong answer. For example,
>
square(5)
[1]
5
These are often
the hardest errors to find because R can’t help you. You haven’t
done something that R doesn’t understand, rather you’ve made an
error telling R what to do. R is doing exactly what you asked, but
it’s not what you meant. Oftentimes to find this error, you need
to go through the function line by line, verifying the result of each
line until you find your error. You can do this either by feeding
each line to the R workspace. Or by writing the result of each line
either to the workspace or to a file using the cat() function.
11. Finally, after correcting all
these errors, your function runs properly:
>
square(5)
[1]
25
No comments:
Post a Comment
Thank you