-
Book Overview & Buying
-
Table Of Contents
R Data Visualization Cookbook
By :
Most of the tasks in R are performed using functions. A function in R has the same utility as functions in Arithmetic.
In order to write a simple function in R, we must first open a new R script by navigating to File | New file.
We write a very simple function that accepts two values and adds them together. Copy and paste the code in the new blank R script:
add = function (x,y){
x+y
}A function in R should be defined by function(). Once we define our function, we need to save it as a .r file. Note that the name of the file should be the same as the function; hence we save our function with name add.r.
In order to use the add() function in the R command window, we need to source the file by using the source() function as follows:
source('<your path>/add.R')Now, we can type add(2,15) in the R command window. You get 17 printed as an output.
The function itself takes two arguments in our recipe but, in reality, it can take many arguments. Anything defined inside curly braces gets executed when we call add(). In our case, we request the user to input two variables, and the output is a simple sum.
Change the font size
Change margin width
Change background colour