Open In App

Apply Function to each Row in R DataFrame

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Apply function to each row in r Dataframe
 
# Creating dataset
# creating first column
x <- c(5, 6, 7, 5, 6, 9)
 
# creating second column
y <- c(6, 4, 3, 4, 2, 6)
 
# creating third column
z <- c(1, 2, 3, 7, 8, 9)
 
# creating dataframe
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




# creating function to computer product
product = function(x, output){
   
  # accessing elements from first column
  A = x[1]
   
  # accessing elements from second column
  B=x[2]
   
  # accessing elements from third column
  C= x[3]
   
  # return product
  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. 

R




# apply(X,MARGIN,FUN,...)
apply(df,1,product  )


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




# apply(X,MARGIN,FUN,...)
single <- apply(df,1,product  )
 
# adding product vector to dataframe
cbind(df,product = single)


Output:

Using apply()

Below is the full implementation:

R




# Apply function to each row in r Dataframe
 
# Creating dataset
# creating firs column
x <- c(5,6,7,5,6,9)
 
# creating second column
y <- c(6,4,3,4,2,6)
 
# creating third column
z <- c(1,2,3,7,8,9)
 
# creating dataframe
df <- data.frame(A=x,B=y,C=z)
 
# creating function to computer product
product = function(x,output){
   
  # accessing elements from first column
  A = x[1]
   
  # accessing elements from second column
  B=x[2]
   
  # accessing elements from third column
  C= x[3]
   
  # return product
  return(A*B*C)
}
 
# apply(X,MARGIN,FUN,...)
apply(df,1,product  )
 
# apply(X,MARGIN,FUN,...)
single <- apply(df,1,product  )
 
# adding product vector to dataframe
cbind(df,product = single)


Output:

Using apply()



Similar Reads

Apply function to each row in Data.table in R
In this article, we are going to see how to apply functions to each row in the data.table in R Programming Language. For applying a function to each row of the given data.table, the user needs to call the apply() function which is the base function of R programming language, and pass the required parameter to this function to be applied in each row
1 min read
Create DataFrame Row by Row in R
In this article, we will discuss how to create dataframe row by row in R Programming Language. Method 1: Using for loop and indexing methods An empty data frame in R language can be created using the data.frame() method in R. For better clarity, the data types of the columns can be defined during the declaration. Each row of the data frame is a vec
4 min read
Divide each dataframe row by vector in R
In this article, we will discuss how to divide each dataframe row by vector in R Programming Language. Method 1 : Using mapply() method The mapply() method can be used to apply a FUN to the dataframe or a matrix, to modify the data. The function specified as the first argument may be any boolean operator, arithmetic, or logical. The operator is the
3 min read
How to calculate the number of occurrences of a character in each row of R DataFrame ?
In this article, we will discuss how to calculate the number of occurrences of a given character in each row in DataFrame in R Programming Language. Method 1: Using stringr package The stringr package in R programming language can be used to perform string manipulations and extraction, which can be installed into the working space. The str_count()
4 min read
Return Column Name of Largest Value for Each Row in R DataFrame
In this article, we will discuss how to return column names of the largest value for each row in DataFrame in R Programming Language. Example: Column1Column2Column3Max columnRow1200Column1 , Because, Column2 value and Column 3 value is less than Column1Row2435Column3 , Because, Column2 value and Column 1 value is less than Column3Row31066Column1 ,
2 min read
Select First Row of Each Group in DataFrame in R
In this article, we will discuss how to select the first row of each group in Dataframe using R programming language. The duplicated() method is used to determine which of the elements of a dataframe are duplicates of other elements. The method returns a logical vector which tells which of the rows of the dataframe are duplicates. Syntax: duplicate
2 min read
Apply function to every value in R dataframe
In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply. Let's understand the problem with the help of an example. Dataset in use: ABCD1.182142.92063.631434.56575.94316.6323 after applying val
4 min read
Use apply Function Only for Specific DataFrame Columns in R
In this article, we are going to apply functions only for specific dataframe columns in the R language. The function in R can be specified using the function keyword, which takes the element x, for instance, as input and modifies each of the elements in x according to the user-defined function. fun &lt;- function(x){ } The pre-defined or user-defin
3 min read
Apply Function to data.table in Each Specified Column in R
In this article, we are going to see that how to apply a function to data.table in each specified column in R Programming Language. The data.table library in R is used to create datasets and represent it in an organized manner. The library can be downloaded and installed into the working space using the following command : install.packages("data.ta
3 min read
Apply a function to each group using Dplyr in R
In this article, we are going to learn how to apply a function to each group using dplyr in the R programming language. The dplyr package in R is used for data manipulations and modifications. The package can be downloaded and installed into the working space using the following command : install.packages("dplyr")What is tibble? A tibble is a data
4 min read