Ideas You Need to Write Simple Function in R Studio

Functions in R

A function is an object in R program. The purpose is repeated tasks you can avoid and improve your productivity. The theory behind is you can give one or more argument 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 statement. One the execution encounters ‘return’, it exits from the function.

The returnobject is the output give back to user.  

More You Need to Know About Functions in R

Simple Function

myfirst <- function()
fib.a <- 1
fib.b <- 1
cat(fib.a,", ",fib.b,", ",sep="")
temp <- fib.a+fib.b
fib.a <- fib.b
fib.b <- temp
cat(fib.b,", ",sep="")
cat("BREAK NOW...")

I have written 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 R command prompt, this function myfirst stores in the workspace.

You know that a functions is also called in object in 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

R Function

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.

Up to now 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 Onine Studio here.

Related Posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.