by2 {quest} | R Documentation |
Apply a Function to Data by Group
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
by2(.data, .vrb.nm, .grp.nm, .sep = ".", .fun, ...)
Arguments
.data |
data.frame of data. |
.vrb.nm |
character vector specifying the colnames of |
.grp.nm |
character vector specifying the colnames of |
.sep |
character vector of length 1 specifying the string to combine the
group values together with. |
.fun |
function to apply to the set of variables |
... |
additional named arguments to pass to |
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
Examples
# 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