For each Row in an R Data Frame

In this tutorial, we shall learn how to apply a function for each Row in an R Data Frame with an example R Script using R apply function.

To call a function for each row in an R data frame, we shall use R apply function.

Syntax – apply()

The syntax of R apply() function is

</>
Copy
apply(data_frame, 1, function, arguments_to_function_if_any)

The second argument 1 represents rows, if it is 2 then the function would apply on columns.

Example 1 – Apply Function for each Row in R DataFrame

Following is an example R Script to demonstrate how to apply a function for each row in an R Data Frame.

r_df_for_each_row.R

</>
Copy
# Learn R program to apply a function for each row in r data frame
# R Data Frame
celebrities = data.frame(name = c("Andrew", "Mathew", "Dany", "Philip", "John", "Bing", "Monica"),
				age = c(28, 23, 49, 29, 38, 23, 29),
				income = c(25.2, 10.5, 11, 21.9, 44, 11.5, 45))
# R function
f = function(x, output) {
	# x is the row of type Character
	# access element in first column
	name = x[1]
	# access element in second column
	income = x[3]
	#your code to process x
	cat(name, income, "\n")
}
#apply(X, MARGIN, FUN, …)
apply(celebrities, 1, f)

Output

$ Rscript r_df_for_each_row.R 
Andrew 25.2 
Mathew 10.5 
Dany 11.0 
Philip 21.9 
John 44.0 
Bing 11.5 
Monica 45.0 
NULL

Conclusion

In this R Tutorial, we have learnt to call a function for each of the rows in an R Data Frame.