#### Example 1: basic usage
# data
df <- data.frame( outcome = 1:6, group1 = c(1,1,1,2,2,2), group2 = c(1,2,1,2,1,2) )
# use xtabs() to obtain a frequency table for group1 x group2:
xtabs( ~ group1 + group2, df )
# group2
# group1 1 2
# 1 2 1
# 2 1 2
# use xfun() to obtain the same frequency table:
xfun( outcome ~ group1 + group2, df, length )
# group2
# group1 1 2
# 1 2 1
# 2 1 2
# use xfun() to find the group means:
xfun( outcome ~ group1 + group2, df, mean )
xfun( formula = outcome ~ group1 + group2, data = df, fun = mean )
# group2
# group1 1 2
# 1 2 2
# 2 5 5
# use xfun() to find the smallest value in each group:
xfun( outcome ~ group1 + group2, df, min )
# group2
# group1 1 2
# 1 1 2
# 2 5 4
#### Example 2: subsetting the data frame
xfun( formula = outcome ~ group1 + group2, data = df, fun = min, subset = -(5:6) )
# group2
# group1 1 2
# 1 1 2
# 2 NA 4
#### Example 3: by default, xfun produces a list of arrays
#### when fun produces a vector of outputs
df2 <- data.frame( outcome = 1:12, group1 = gl(3,4), group2 = gl(2,1,12) )
xfun( outcome ~ group1 + group2, df2, range )
xfun( outcome ~ group1 + group2, df2, ciMean )
#### Example 4: if split=FALSE, or if the output of fun is
#### not a vector, then xfun reverts to an array of mode list,
#### as per the tapply function:
xfun( outcome ~ group1 + group2, df2, ciMean, split=FALSE )
#### Example 5: if fun returns outputs of different lengths
#### for different groups, the remaining entries are padded
#### with NAs:
xfun( formula = outcome ~ group1 + group2, data = df, fun = c )
Run the code above in your browser using DataLab