Applying functions to matrix rows and columns in R programming
Applying functions to matrix rows and columns in R programming allows us to perform operations on the elements of the matrix along rows or columns. This can be useful for tasks like calculating row or column means, standard deviations, or other summary statistics.
These
are the different ways to apply functions to matrix rows and columns in R
programming.
One of the most famous and most used
features of R is the *apply() family of functions, such as apply(), tapply(),
and lapply()etc….
A. Using apply() function:
The apply() function applies a function to the rows or columns of a matrix.
Syntax: apply(X,
MARGIN, FUN, ...)
Parameters :
X:
the matrix or array
MARGIN:
1 for rows and 2 for columns
FUN:
the function to be applied
...:
additional arguments to the function
B. Using sapply() function:
The sapply() function is similar to
apply() function but it returns a vector instead of a matrix.
Syntax: sapply(X,
FUN, ...)
Parameters :
X:
the matrix or array
FUN:
the function to be applied
...:
additional arguments to the function
C. Using lapply() function:
The lapply() function applies a
function to each element of a list or a matrix. The syntax for lapply()
function is as follows:
Syntax: lapply(X,
FUN, ...)
Parameters :
X:
the matrix or array
FUN:
the function to be applied
...:
additional arguments to the function
D. Using rowSums() and colSums() functions:
The rowSums() function
computes the sum of each row of a matrix and returns a vector. The colSums()
function computes the sum of each column of a matrix and returns a vector. The
syntax for these functions is as follows:
Syntax: rowSums(x,
na.rm = FALSE)
colSums(x,
na.rm = FALSE)
Parameters :
x:
the matrix or array
na.rm:
logical indicating whether missing values should be removed
Example :
mat <- matrix(1:9, nrow=3, ncol=3) # Create a matrix
colSums
<- apply(mat, 2, sum) #
Apply the sum function to each column
rowSums
<- sapply(mat, sum) #
Apply the sum function to each row and return a vector
#
Apply the sqrt function to each element of the matrix and return a matrix
sqrtMat
<- matrix(unlist(lapply(mat, sqrt)), nrow=3, ncol=3)
rowSums
<- rowSums(mat) #
Compute the sum of each row
colSums
<- colSums(mat) #
Compute the sum of each column
cat("Original
matrix:\n") #
Print the results
print(mat)
cat("Column
sums:\n")
print(colSums)
cat("Row
sums:\n")
print(rowSums)
cat("Square
root of matrix:\n")
print(sqrtMat)
Output
:
[,1]
[,2] [,3]
[1,]
1 4 7
[2,]
2 5 8
[3,]
3 6 9
rowSums:
12 15 18
colSums:
6 15 24
sqrtMat:
[,1]
[,2] [,3]
[1,]
1.000000 2.000000 2.645751
[2,]
1.414214 2.236068 2.828427
No comments:
Post a Comment