The “across” Function in R
Package: dplyr
Purpose: To apply a function to multiple columns in a data frame.
General Class: Data Manipulation
Required Argument(s):
cols: Columns to apply the function to.
Notable Optional Arguments:
.fns: A function or a list of functions to apply to the selected columns.
...: Additional arguments passed to the functions specified in .fns.
Example (with Explanation):
# Load necessary packages
library(dplyr)
# Create a sample data frame
data <- data.frame(
ID = c(1, 2, 3),
value1 = c(10, 15, 20),
value2 = c(25, 30, 35)
)
# Apply the mean function to value1 and value2 columns
result <- data %>%
summarise(across(c(value1, value2), mean))
# Display the result
print(result)In this example, the across function from the dplyr package is used to apply the mean function to the ‘value1’ and ‘value2’ columns in the sample data frame data. The summarise function is then used to compute the mean for each selected column. The result is a new data frame with one row containing the mean value for each selected column.