Open In App

Apply function to each row in Data.table in R

Improve
Improve
Like Article
Like
Save
Share
Report

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 of the given data.table in R language.

apply() function returns a vector or array or list of values obtained by applying a function to the margins of an array or matrix.

Syntax:

apply(X, MARGIN, FUN, …)

Parameters:

  • X: an array, including a matrix.
  • MARGIN: a vector giving the subscripts which the function will be applied over.
  • FUN: the function to be applied: see ‘Details’. In the case of functions like +, %*%, etc., the function name must be backquoted or quoted.
  • …: optional arguments to FUN.

Example 1:

R




library(data.table)
    
gfg_data <- data.table(x = c(1,2,3,4,5),  
                       y = c(4,3,2,5,1),
                       z=c(2,3,5,4,1))
  
gfg_data         
apply(gfg_data, 1, sum)


Output:

[1]  7  8 10 13  7

Example 2:

R




library(data.table)
  
gfg_data <- data.table(x = c(1,2,3,4,5), 
                       y = c(4,3,2,5,1),
                       z=c(2,3,5,4,1))
  
gfg_data  
apply(gfg_data, 1, max)


Output:

[1] 4 3 5 5 5


Last Updated : 30 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads