Learn R Programming

informR (version 1.0-5)

glapply: Group Level Apply

Description

Apply a function on a variable over levels of an grouping factor. A wrapper for split() and is similar in functionality to by() but with more options for output.

Usage

glapply(x, id, FUN, regroup = TRUE, ...)

Arguments

x
a string or numeric vector.
id
grouping factor with length(x)
FUN
Function to apply over x
regroup
logical, if TRUE returns result in the same structure as x, otherwise, returns a list of length unique(id).
...
Additional arguments passed to FUN

See Also

split,unsplit,lapply

Examples

Run this code
data(Indometh)
glapply(Indometh$conc,Indometh$Subject,FUN=mean)
x<-rep(sample(1:10),2)
id<-rep(letters[1:5],4)
glapply(x,id,FUN=function(x)sum((x-mean(x))^2),regroup=FALSE)
glapply(x,id,FUN=function(x)sum((x-mean(x))^2),regroup=TRUE)
#Compare with output produced by by()
by(x,id,function(x)sum((x-mean(x))^2))

Run the code above in your browser using DataLab