R Passing Several Parameters to apply Functions (Example Code)
On this page you’ll learn how to pass several parameters to the family of apply functions in the R programming language.
Creation of Example Data
data(iris) # Loading iris data iris_new <- iris[ , 1:4] # Modify iris data iris_new$Sepal.Length[1] <- NA head(iris_new) # Head of modified iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 NA 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 |
data(iris) # Loading iris data iris_new <- iris[ , 1:4] # Modify iris data iris_new$Sepal.Length[1] <- NA head(iris_new) # Head of modified iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 NA 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: Specifying Multiple Arguments in apply() Function
apply(iris_new, # No additional arguments 2, sum) # Sepal.Length Sepal.Width Petal.Length Petal.Width # NA 458.6 563.7 179.9 |
apply(iris_new, # No additional arguments 2, sum) # Sepal.Length Sepal.Width Petal.Length Petal.Width # NA 458.6 563.7 179.9
apply(iris_new, # Multiple arguments 2, sum, na.rm = TRUE) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 871.4 458.6 563.7 179.9 |
apply(iris_new, # Multiple arguments 2, sum, na.rm = TRUE) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 871.4 458.6 563.7 179.9