Categories: Data Science

Learn R – How to Define Function in R

This article represents code examples in relation with how to write function in R. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.

Following are the key points described later in this article:

  • Function Definition
  • Code Examples for Functions

 

How to Define Function

Function in R looks like following:

# Function definition
funcName <- function( a, b, c ) {
    return(v) # or simply v
}
# This is how a function is invoked
var1 <- funcName(x,y,x) 

In above code, funcName is the name of the function. a, b, c are parameters. v is return variable

Code Examples for Functions

In the examples below, following four functions are demonstrated:

  • Create an empty Data Frame
  • Add/Append a vector to the data frame
  • Search for a vector in the data frame
  • Print first n rows in the data frame
# Creates an empty Data Frame with two columns namely, Name and Age
# Return the newly created empty data frame with 0 row
createDF <- function() {
  df <- data.frame(name=character(), age=numeric(), stringsAsFactors=F)
  return(df)
}

# Add the vector, c, to the passed data frame, df
# Return the updated data frame
addToDF <- function( df, c) {
  df[nrow(df) + 1,] <- c
  return(df)
}

# Search the data frame for existence of values in vector cv
# Return true if found, else false
searchFromDF <- function( df, cv ) {
  found <- F
  for( i in 1:nrow(df) ) {
    if( df$name[i] == cv[1] && df$age[i] == cv[2] ) {
      found <- T
      break
    }
  }
  found
}

# Print first n rows of the dataframe
phead <- function(df, n) {
  for( i in 1:nrow(df)) {
    if( i < n+1) {
      cat(df[i,]$name,"\t",df[i,]$age,"\n")
    }
  }
}

Following is how the above functions would be invoked:

# Creates an empty data frame
df1 <- createDF()

# Add the vector to the the data frame
df1 <- addToDF(df1, c("Ajitesh", 38))
df1 <- addToDF(df1, c("Aiyana", 9))
df1 <- addToDF(df1, c("Anisha", 4))

# Prints True
searchFromDF(df1, c("Aiyana", 9))
# Prints False
searchFromDF(df1, c("Anisha", 41))

# Prints first 2 rows of the dataframe df1
phead(df1, 2)


 

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com

Recent Posts

Model Selection by Evaluating Bias & Variance: Example

When working on a machine learning project, one of the key challenges faced by data…

4 hours ago

Bias-Variance Trade-off in Machine Learning: Examples

Last updated: 1st May, 2024 The bias-variance trade-off is a fundamental concept in machine learning…

22 hours ago

Mean Squared Error vs Cross Entropy Loss Function

Last updated: 1st May, 2024 As a data scientist, understanding the nuances of various cost…

22 hours ago

Cross Entropy Loss Explained with Python Examples

Last updated: 1st May, 2024 In this post, you will learn the concepts related to…

22 hours ago

Logistic Regression in Machine Learning: Python Example

Last updated: 26th April, 2024 In this blog post, we will discuss the logistic regression…

6 days ago

MSE vs RMSE vs MAE vs MAPE vs R-Squared: When to Use?

Last updated: 22nd April, 2024 As data scientists, we navigate a sea of metrics to…

1 week ago