Saturday, April 28, 2012

How to write, save, and call your own functions in R With an Example



·         How to write?
                General form of function is
NameOfFun <- function(argument1,argument2...)
            {
                        Your expressions go here
            }
name <- function(x,y,..)
            {
                        if(.....) do something to x and or y
                        if(.....) do something to ............
            }
·         How to save?
                1- From R, write or paste your function code in R Editor or R script
                2- Save your function as "nameOfFile.R" in your working directory
                               
·         How to Call?
1-  in R Console type source("nameOfFile.R")

I have written a function that automatically assign letter grades. You can copy the function from
Or you can follow the following steps that may help you to know how to call a function:-
1- Download the function from
2- Unzip the folder and copy the file "GradingFunction.R" into your working Directory
3- Go to R, and type
source("GradingFunction.R") to call the function
4- If you are a TA and would like to try the function in your classes, follow the arguments of function as explained here
5- I have also randomly generated grades if you wish to try the function. There are two examples from the above link.

Note: This function may not directly related  to Data Analysis, but the process is the same (e.g., you want to assign labels into your grouping variables if conditions satisfied) 

Adil

No comments:

Post a Comment