Following are the key points described later in this article:
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
In the examples below, following four functions are demonstrated:
# 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)
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…
Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…
Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…
The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…
Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…