A function is an object in the R program. The purpose is repeated tasks you can avoid and improve your productivity. The theory behind this is you can give one or more arguments in input and you can get one or more values as Return.
Syntax to Write Function in R studio
functionname <- function(arg1,arg2,arg3,...)
{ do any code in here when called return(returnobject)}
The functionname is a valid name in R. The symbol ‘<-‘ you can say as assigning the name to function. In the above syntax. There are three arguments.
The code inside of braces is called ‘Body’. You can give one or more calls to return statements. Once the execution encounters ‘return’, it exits from the function.
The returned object is the output given back to the user.
Simple Function
myfirst <- function()
{
fib.a <- 1
fib.b <- 1
cat(fib.a,", ",fib.b,", ",sep="")
repeat{
temp <- fib.a+fib.b
fib.a <- fib.b
fib.b <- temp
cat(fib.b,", ",sep="")
if(fib.b>150){
cat("BREAK NOW...")
break
}
}}
I have written a function called myfirst , and it does not have any arguments. There are two variables fib.a and fib.b.
The cat() functions to display information to the terminal or user. When you run the above code in the R command prompt, this function myfirst stores in the workspace.
You know that a function is also called an object in the R language. This object you can see using ls() function.
ls() function shows the objects present in the current workspace
The ls() function showing in R Studio
The last line “myfirst” shows the function is imported to the workspace. The command we used is ls().
How Function Works in R Language
> myfirst()
In the above line, I have not passed any arguments. Since, while creating a function I did not pass any arguments.
So far you are good…
Result of MYFIRST function
[1] "myfirst" 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...
The ‘break’ statement says to exit from the function. The ‘sep=’ function adds one space.
RStudio On line Compiler
You can work on R Online Studio here.
You must be logged in to post a comment.