Apply Function to Every Row of Data Frame or Matrix in R (Example)

 

On this page you’ll learn how to use a function for each row of a data frame or matrix in the R programming language.

The page is structured as follows:

Let’s jump right to the examples!

 

Creating Example Data

We’ll use the following data frame as example data:

data <- data.frame(x1 = 1:5,        # Create example data
                   x2 = 2:6,
                   x3 = 3:7)
data                                # Print data to console
#   x1 x2 x3
# 1  1  2  3
# 2  2  3  4
# 3  3  4  5
# 4  4  5  6
# 5  5  6  7

Our example data consists of five rows and tree variables x1, x2, and x3.

Now, let’s apply a function to each row of this data table…

 

Example: Use Function for Each Row of Data Frame in R

If we want to apply a function to every row of a data frame or matrix, we can use the apply() function of Base R. The following R code computes the sum of each row of our data and returns it to the RStudio console:

apply(data, 1, sum)                 # Apply function to each row
# 6  9 12 15 18

The sum of the first row is 6, the sum of the second row is 9, and so on…

Note that within the apply function you have to specify three things:

  • The name of the data frame or matrix that we want to use (i.e. data).
  • Whether we want to apply a function by column or by row. 1 indicates by row; 2 indicates by column.
  • The function we want to apply (i.e. sum).

In this example, we applied the sum function to every row of the data table. However, you may use any function within the apply command that you want.

 

Video, Further Resources & Summary

If you need more info on the R codes of this tutorial, you might have a look at the following video of my YouTube channel. I show the contents of this article in the video:

 

 

Furthermore, you may want to have a look at the other tutorials of my homepage. Some articles can be found below.

 

This tutorial explained how to apply the same function to each row of a data frame or matrix in the R programming language. Tell me about it in the comments, in case you have further questions. Furthermore, don’t forget to subscribe to my email newsletter to get updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top