by2: Apply a Function to Data by Group

Description Usage Arguments Value See Also Examples

View source: R/quest_functions.R

Description

by2 applies a function to data by group and is an alternative to the base R function by. The function is apart of the split-apply-combine type of function discussed in the plyr R package and is very similar to dlply. It splits up one data.frame .data[.vrb.nm]into a data.frame for each group in .data[.grp.nm], applies a function .fun to each data.frame, and then returns the results as a list with names equal to the group values unique(interaction(.data[.grp.nm], sep = .sep)). by2 is simply split.data.frame + lapply. Similar to dlply, The arguments all start with . so that they do not conflict with arguments from the function .fun. If you want to apply a function a (atomic) vector rather than data.frame, then use tapply2.

Usage

1
by2(.data, .vrb.nm, .grp.nm, .sep = ".", .fun, ...)

Arguments

.data

data.frame of data.

.vrb.nm

character vector specifying the colnames of .data to select the set of variables to apply .fun to.

.grp.nm

character vector specifying the colnames of .data to select the grouping variables.

.sep

character vector of length 1 specifying the string to combine the group values together with. .sep is only used if there are multiple grouping variables (i.e., length(.grp.nm) > 1).

.fun

function to apply to the set of variables .data[.vrb.nm] for each group.

...

additional named arguments to pass to .fun.

Value

list of objects containing the return object of .fun for each group. The names are the unique combinations of the grouping variables (i.e., unique(interaction(.data[.grp.nm], sep = .sep))).

See Also

by tapply2 dlply

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# one grouping variable
by2(mtcars, .vrb.nm = c("mpg","cyl","disp"), .grp.nm = "vs",
   .fun = cov, use = "complete.obs")

# two grouping variables
x <- by2(mtcars, .vrb.nm = c("mpg","cyl","disp"), .grp.nm = c("vs","am"),
   .fun = cov, use = "complete.obs")
print(x)
str(x)

# compare to by
vrb_nm <- c("mpg","cyl","disp") # Roxygen runs the whole script if I put a c() in a []
grp_nm <- c("vs","am") # Roxygen runs the whole script if I put a c() in a []
y <- by(mtcars[vrb_nm], INDICES = mtcars[grp_nm],
   FUN = cov, use = "complete.obs", simplify = FALSE)
str(y) # has dimnames rather than names

quest documentation built on Sept. 10, 2021, 5:07 p.m.

Related to by2 in quest...