Learn R Programming

memisc (version 0.99.21)

Groups: Operate on grouped data in data frames and data sets

Description

Group creates a grouped variant of an object of class "data.frame" or of class "data.set", for which methods for with and within are defined, so that these well-known functions can be applied "groupwise".

Usage

# Create an object of class "grouped.data" from a
# data frame or a data set.
Groups(data,by,…)
# S4 method for data.frame,formula
Groups(data,by,…)
# S4 method for data.set,formula
Groups(data,by,…)

# Recombine grouped data into a data fame or a data set recombine(x,…) # S3 method for grouped.data recombine(x,…)

# Methods of the generics "with" and "within" for grouped data # S3 method for grouped.data with(data,expr,…) # S3 method for grouped.data within(data,expr,recombine=FALSE,…) # S3 method for grouped.data names(x)

# This is equivalent to with(Groups(data,by),expr,...) withGroups(data,by,expr,…) # This is equivalent to within(Groups(data,by),expr,recombine,...) withinGroups(data,by,expr,recombine=TRUE,…)

Arguments

data

an object of the classes "data.frame", "data.set" if an argument to Groups, withGroups, withinGroups,

by

a formula with the factors the levels of which define the groups.

expr

an expression, or several expressions enclosed in curly braces.

recombine

a logical vector; should the resulting grouped data be recombined?

x

an object of class "grouped.data".

other arguments, ignored.

Examples

Run this code
# NOT RUN {
some.data <- data.frame(x=rnorm(n=100))
some.data <- within(some.data,{
    f <- factor(rep(1:4,each=25),labels=letters[1:4])
    g <- factor(rep(1:5,each=4,5),labels=LETTERS[1:5])
    y <- x + rep(1:4,each=25) +  0.75*rep(1:5,each=4,5)
})


some.grouped.data <- Groups(some.data,
                           ~f+g)    

group.means <- with(some.grouped.data,
                    mean(y))
group.means

some.grouped.data <- within(some.grouped.data,{
    y.cent <- y - mean(y)
},recombine=FALSE)

group.means <- with(some.grouped.data,
                    round(mean(y.cent),15))
group.means

str(group.means)

with(some.grouped.data,
     c(Centered=round(mean(y.cent),15),
       Uncentered=mean(y)))

some.data.ungrouped <- recombine(some.grouped.data)
str(some.data.ungrouped)

some.dataset <- as.data.set(some.data)
some.grouped.dataset <- Groups(some.dataset,~f+g)

with(some.grouped.dataset,
     c(Mean=mean(y),
       Variance=var(y)))


with(Groups(some.data,~f+g),mean(y))

some.data <- within(Groups(some.data,~f+g),{
    y.cent <- y - mean(y)
},recombine=TRUE)

round(with(some.data,
           tapply(y.cent,list(g,f),
                  mean,na.rm=TRUE)),15)

some.data <- withinGroups(some.data,~f+g,{
    y.cent <- y - mean(y)
})

round(with(some.data,
           tapply(y.cent,list(g,f),
                  mean)),15)


withGroups(some.data,~f+g,{
    round(mean(y.cent),15)
})
# }

Run the code above in your browser using DataLab