Apply a Function to Subset of Variables in a Dataset Based on Root Names
Source:R/root_apply.R
root_apply.Rd
The root_apply
function takes a dataset and a vector of root names
and applies a specified function to the subset of variables that match each root name
and have a number at the end of their name. It returns a list of the results
for each root name. If the function fails for a particular root name,
it returns NA for that root name and prints a message with the error.
Arguments
- dataset
A dataset where the function needs to be applied.
- root_names
A character vector of root names.
- fun
The function to apply to the subset of variables for each root name.
- ...
Additional arguments to the function.
Value
A list where each element is the result of applying fun
to the subset
of variables that match a root name and have a number at the end of their name.
Each element in the list is named after the root name.
Examples
if (FALSE) {
# Generate some data
df <- data.frame(
daily_sat_aut_1 = rnorm(100),
daily_sat_aut_2 = rnorm(100),
daily_fru_aut_1 = rnorm(100),
daily_fru_aut_2 = rnorm(100),
daily_sat_rel_1 = rnorm(100),
daily_sat_rel_2 = rnorm(100),
daily_fru_rel_1 = rnorm(100),
daily_fru_rel_2 = rnorm(100)
)
# Apply the mean function to the subsets of variables
results <- root_apply(df,
root_names = c("daily_sat_aut_reversed", "daily_fru_aut", "daily_sat_rel"),
fun = mean)
}