tapply2: Apply a Function to a (Atomic) Vector by Group

Description Usage Arguments Value See Also Examples

View source: R/quest_functions.R

Description

tapply2 applies a function to a (atomic) vector by group and is an alternative to the base R function tapply. The function is apart of the split-apply-combine type of function discussed in the plyr R package and is somewhat similar to dlply. It splits up one (atomic) vector .xinto a (atomic) vector for each group in .grp, applies a function .fun to each (atomic) vector, and then returns the results as a list with names equal to the group values unique(interaction(.grp.nm, sep = .sep)). tapply2 is simply split.default + 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 data.frame rather than a (atomic) vector, then use by2.

Usage

1
tapply2(.x, .grp, .sep = ".", .fun, ...)

Arguments

.x

atomic vector

.grp

list of atomic vector(s) and/or factor(s) (e.g., data.frame) containing the groups. They should each have same length as .x. It can also be an atomic vector or factor, which will then be made the first element of a list internally.

.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., .grp is a list with multiple elements).

.fun

function to apply to .x 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(.grp, sep = .sep))).

See Also

tapply by2 dlply

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# one grouping variable
tapply2(mtcars$"cyl", .grp = mtcars$"vs", .fun = median, na.rm = TRUE)

# two grouping variables
grp_nm <- c("vs","am") # Roxygen runs the whole script if I put a c() in a []
x <- tapply2(mtcars$"cyl", .grp = mtcars[grp_nm], .fun = median, na.rm = TRUE)
print(x)
str(x)

# compare to tapply
grp_nm <- c("vs","am") # Roxygen runs the whole script if I put a c() in a []
y <- tapply(mtcars$"cyl", INDEX = mtcars[grp_nm],
   FUN = median, na.rm = TRUE, simplify = FALSE)
print(y)
str(y) # has dimnames rather than names

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

Related to tapply2 in quest...