How to Compute the Standard Deviation Across Rows in R (Example Code)

In this R programming article you’ll learn how to get the standard deviation across rows of a data matrix.

Creating Example Data

data(iris)                      # Load and modify example data
my_iris <- iris[ , 1:4]
head(my_iris)                   # Head of example data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1          5.1         3.5          1.4         0.2
# 2          4.9         3.0          1.4         0.2
# 3          4.7         3.2          1.3         0.2
# 4          4.6         3.1          1.5         0.2
# 5          5.0         3.6          1.4         0.2
# 6          5.4         3.9          1.7         0.4

Example: Compute Standard Deviation Across Rows Using apply() Function

my_iris_sd <- cbind(my_iris,    # Standard deviations across rows
                    sd_by_row = apply(my_iris, 1, sd))
head(my_iris_sd)                # Display head of data with sd
#   Sepal.Length Sepal.Width Petal.Length Petal.Width sd_by_row
# 1          5.1         3.5          1.4         0.2  2.179449
# 2          4.9         3.0          1.4         0.2  2.036950
# 3          4.7         3.2          1.3         0.2  1.997498
# 4          4.6         3.1          1.5         0.2  1.912241
# 5          5.0         3.6          1.4         0.2  2.156386
# 6          5.4         3.9          1.7         0.4  2.230844

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.
You need to agree with the terms to proceed

Menu
Top