Using apply() Function by Row & Column in R (2 Examples)
In this R programming post you’ll learn how to use the apply command.
Creating Example Data
data(iris) # Loading iris data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading iris data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example 1: Using apply() Function by Row
apply(iris[ , 1:4], 1, mean) # apply function by row # 2.550 2.375 2.350 2.350 2.550 2.850 2.425 2.525 2.225 2.400 2.700 2.500 2.325 2.125 ... |
apply(iris[ , 1:4], 1, mean) # apply function by row # 2.550 2.375 2.350 2.350 2.550 2.850 2.425 2.525 2.225 2.400 2.700 2.500 2.325 2.125 ...
Example 2: Using apply() Function by Column
apply(iris, 2, is.numeric) # apply function by column # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # FALSE FALSE FALSE FALSE FALSE |
apply(iris, 2, is.numeric) # apply function by column # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # FALSE FALSE FALSE FALSE FALSE