Function
In R, a function is a reusable blo ck of code designed to perform a specific task. Functions
take inputs (arguments), process them, and return outputs or perform actions. Functions help
to write modular and efficient code by encapsulating repeated tasks into callable units.
Types of Functions in R
1. Built-in functions: Provided by R for common tasks (e.g., mean(), sum(), print()).
2. User-defined functions: Created by users for custom tasks.
Syntax to Define a Function
function_name <- function(arg1, arg2, ...) {
# Code block
# Perform operations
return(result) # Optional: Returns the output
Parameters or Arguments?
The terms "parameter" and "argument" can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
In R, local variables are defined within a function and are only accessible within that function's
scope, while global variables exist outside of functions and can be accessed anywhere in the script or
environment.
Local Variable
A local variable is created inside a function and is not accessible outside that function.
# Define a function with a local variable
my_function <- function() {
local_var <- 10 # Local variable
print(paste("Inside function, local_var:", local_var))
}
# Call the function
my_function()
# Try to access the local variable outside the function
print(local_var) # Error: object 'local_var' not found
Output:
Inside the function: Inside function, local_var: 10
Outside the function: Error: object 'local_var' not found
Single Return Value
# Define a function
square <- function(x) {
return(x^2) # Explicit return statement
# Call the function
result <- square(4)
print(result) # Output: 16
Returning Multiple Values
# Define a function
calculate <- function(a, b) {
sum_val <- a + b
diff_val <- a - b
prod_val <- a * b
return(list(sum = sum_val, difference = diff_val, product = prod_val))
# Call the function
result <- calculate(10, 5)
# Access individual values
print(result$sum) # Output: 15
print(result$difference) # Output: 5
print(result$product) # Output: 50
Conditional Returns
# Define a function
classify_number <- function(x) {
if (x > 0) {
return("Positive")
} else if (x < 0) {
return("Negative")
} else {
return("Zero")
# Call the function
result1 <- classify_number(5)
result2 <- classify_number(-3)
result3 <- classify_number(0)
print(result1) # Output: "Positive"
print(result2) # Output: "Negative"
print(result3) # Output: "Zero"
# Example data
data <- c(1, 2, 2, 3, 4, 6, 8, 9, 10)
Mean, Variance, Skewness and Kurtosis Manual Calculation
calculate mean, variance, skewness, and kurtosis in R using raw moments and central
moments.
📘 Definitions:
✅ Raw moments (about origin):
' 1
μ 1= ∑ x i (mean)
n
' 1 2
μ 2= ∑ x i
n
' 1 3
μ 3= ∑ x i
n
' 1 4
μ 4 = ∑ xi
n
✅ Central moments (about mean):
1
μ2 = ∑ ¿
n
1
μ3 = ∑ ¿
n
1
μ4 = ∑ ¿
n
✅ R Function Using Raw and Central Moments
my_stats_moments <- function(x) {
n <- length(x)
# Raw moments
m1_raw <- sum(x) / n
m2_raw <- sum(x^2) / n
m3_raw <- sum(x^3) / n
m4_raw <- sum(x^4) / n
# Central moments
mu2 <- m2_raw - m1_raw^2
mu3 <- m3_raw - 3 * m1_raw * mu2 - m1_raw^3
mu4 <- m4_raw - 4 * m1_raw * m3_raw + 6 * m1_raw^2 * m2_raw - 3 *
m1_raw^4
# Standard deviation
sd_x <- sqrt(mu2)
# Skewness and kurtosis (population formulas)
skewness <- mu3 / sd_x^3
kurtosis <- mu4 / sd_x^4 - 3 # Excess kurtosis
return(list(
mean = m1_raw,
variance = mu2,
skewness = skewness,
kurtosis = kurtosis
))
}
✅ Example Use
x <- c(2, 4, 6, 8, 10)
my_stats_moments(x)
✅ Why This Is Useful
This method is theoretical, showing the link between raw and central moments.
It's the foundation for moment-based descriptive statistics and probability
distributions.
# Calculate skewness
n <- length(data)
mean_val <- mean(data)
sd_val <- sd(data)
skew <- (sum((data - mean_val)^3) / n) / (sd_val^3)
print(skew)
# Calculate kurtosis
kurt <- (sum((data - mean_val)^4) / n) / (sd_val^4) - 3 # Excess kurtosis
print(kurt)
Interpretation
1. Skewness:
o Positive: Data is skewed to the right (longer tail on the right).
o Negative: Data is skewed to the left (longer tail on the left).
o Zero: Data is symmetric.
2. Kurtosis:
o Positive excess kurtosis (>0): Leptokurtic (sharp peak).
o Negative excess kurtosis (<0): Platykurtic (flat distribution).
o Zero excess kurtosis: Mesokurtic (normal distribution).
# Define the function
moments_summary <- function(data) {
# Ensure the input is a numeric vector
if () {
stop("Input data must be numeric.")
# Calculate the mean
mean_val <- mean(data)
# Calculate the variance
variance_val <- var(data) # Uses (n-1) denominator
# Calculate the third central moment
n <- length(data)
third_central_moment <- sum((data - mean_val)^3) / n
# Calculate skewness
skewness_val <- third_central_moment / (sqrt(variance_val)^3)
# Calculate the fourth central moment
fourth_central_moment <- sum((data - mean_val)^4) / n
# Calculate kurtosis (excess kurtosis)
kurtosis_val <- (fourth_central_moment / (variance_val^2)) - 3
# Return results as a named list
return(list(
mean = mean_val,
variance = variance_val,
third_central_moment = third_central_moment,
skewness = skewness_val,
kurtosis = kurtosis_val
))
}
# Example dataset
data <- c(1, 2, 2, 3, 4, 6, 8, 9, 10)
# Call the custom function
result <- moments_summary(data)
# Print the results
print(result)
$mean
[1] 5
$variance
[1] 11.25
$third_central_moment
[1] 7.407407
$skewness
[1] 0.6324555
$kurtosis
[1] -1.178571
####Package Installation
[Link]("moments")
library(moments)
# Example data
data <- c(1, 2, 2, 3, 4, 6, 8, 9, 10)
# Calculate skewness
skew <- skewness(data)
print(skew) # Positive skew
# Calculate kurtosis
kurt <- kurtosis(data)
print(kurt) # Excess kurtosis
[Link]("e1071")
library(e1071)
# Example data
data <- c(1, 2, 2, 3, 4, 6, 8, 9, 10)
# Calculate skewness
skew <- skewness(data)
print(skew)
# Calculate kurtosis
kurt <- kurtosis(data)
print(kurt)
[Link]("psych")
library(psych)
# Example data
data <- c(1, 2, 2, 3, 4, 6, 8, 9, 10)
# Describe the data
desc <- describe(data)
print(desc)
# Access skewness and kurtosis
skew <- desc$skew
kurt <- desc$kurtosis
print(skew)
print(kurt)
rbind and cbind
In R, rbind and cbind are functions used to combine vectors, matrices, or data frames by
rows or columns, respectively:
1. rbind (Row Bind):
Combines data by adding rows.
It stacks vectors, matrices, or data frames vertically.
rbind(object1, object2, ...)
# Combining two vectors by rows
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
rbind(vec1, vec2)
# Output:
# [,1] [,2] [,3]
# vec1 1 2 3
# vec2 4 5 6
# Combining data frames by rows
df1 <- [Link](A = c(1, 2), B = c(3, 4))
df2 <- [Link](A = c(5, 6), B = c(7, 8))
rbind(df1, df2)
# Output:
# AB
#113
#224
#357
#468
2. cbind (Column Bind):
Combines data by adding columns.
It stacks vectors, matrices, or data frames horizontally.
cbind(object1, object2, ...)
# Combining two vectors by columns
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
cbind(vec1, vec2)
# Output:
# vec1 vec2
# [1,] 1 4
# [2,] 2 5
#[
Raw name and column Name Rename
Random Number Generate s