Apply Function to each Row in R DataFrame
In this article, we will discuss how to apply a function to each row in a data frame in R Programming Language. Let’s take an example for a better understanding.
Example:
Suppose we have a dummy dataset with A, B, C as column names and some numeric value as rows.
|
A
|
B
|
C
|
1.
|
5
|
6
|
1
|
2.
|
6
|
4
|
2
|
3.
|
7
|
3
|
3
|
4.
|
5
|
4
|
7
|
5.
|
6
|
2
|
8
|
6.
|
9
|
6
|
9
|
And we want to apply a function that will return the product of each row value, then the resultant data frame should look like this:
|
A
|
B
|
C
|
product
|
1.
|
5
|
6
|
1
|
60
|
2.
|
6
|
4
|
2
|
48
|
3.
|
7
|
3
|
3
|
63
|
4.
|
5
|
4
|
7
|
140
|
5.
|
6
|
2
|
8
|
96
|
6.
|
9
|
6
|
9
|
486
|
Apply function to each row in R Data frame:
Approach: Using apply function
apply() is used to compute a function on a data frame or matrix. The purpose of using apply() function is to avoid the use of looping. apply() function returns output as a vector.
Syntax: apply(x, margin, func)
Parameters:
x: Array or matrix
margin: dimension on which operation is to be applied
func: operation to be applied
Stepwise implementation:
Step 1: Create a dummy dataset.
R
x <- c (5, 6, 7, 5, 6, 9)
y <- c (6, 4, 3, 4, 2, 6)
z <- c (1, 2, 3, 7, 8, 9)
df <- data.frame (A = x, B = y, C = z)
display (df)
|
Output:
A B C
1 5 6 1
2 6 4 2
3 7 3 3
4 5 4 7
5 6 2 8
6 9 6 9
Step 2: Create a custom function for calculating products.
R
product = function (x, output){
A = x[1]
B=x[2]
C= x[3]
return (A*B*C)
}
|
Note: Here we are just defining the function for computing product and not calling, so there will be no output until we call this function.
Step 3: Use apply the function to compute the product of each row.
Syntax: (data_frame, 1, function,…)
Now we are calling the newly created product function and returns the product using apply function.
Output:
[1] 30 48 63 140 96 486
Note: apply() return product as a vector list. So we have to add it to the data frame using cbind (column bind).
Step 4: Append product list to the data frame.
R
single <- apply (df,1,product )
cbind (df,product = single)
|
Output:
Using apply()
Below is the full implementation:
R
x <- c (5,6,7,5,6,9)
y <- c (6,4,3,4,2,6)
z <- c (1,2,3,7,8,9)
df <- data.frame (A=x,B=y,C=z)
product = function (x,output){
A = x[1]
B=x[2]
C= x[3]
return (A*B*C)
}
apply (df,1,product )
single <- apply (df,1,product )
cbind (df,product = single)
|
Output:
Using apply()
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...