• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Analysis Factor

The Analysis Factor

Statistical Consulting, Resources, and Statistics Workshops for Researchers

  • Home
  • About
    • Our Programs
    • Our Team
    • Our Core Values
    • Our Privacy Policy
    • Employment
    • Guest Instructors
  • Membership
    • Statistically Speaking Membership Program
    • Login
  • Workshops
    • Online Workshops
    • Login
  • Consulting
    • Statistical Consulting Services
    • Login
  • Free Webinars
  • Contact
  • Login

R Is Not So Hard! A Tutorial, Part 10: Creating Summary tables with aggregate()

by guest 6 Comments

by David Lillis, Ph.D.

In Part 10, let’s look at the aggregate command for creating summary tables using R.

You may have a complex data set that includes categorical variables of several levels, and you may wish to create summary tables for each level of the categorical variable.

For example, your data set may include the variable Gender, a two-level categorical variable with levels Male and Female. Your data set may include other categorical variables such as Ethnicity, Hair Colour, the Treatments received by patients in a medical study, or the number of cylinders in motor vehicles.

In any case, you may wish to produce summary statistics for each level of the categorical variable. This is where the aggregate command is so helpful.

Here is a data set of patients receiving medical treatment (A, B or C). We have data on their gender, their body mass in kg, whether or not they exercise, whether or not they smoke, and whether or not they recovered after treatment. Cut and paste the following data set into R.

attach(patients)
patients

GENDER TREATMENT MASS SMOKE EXERCISE RECOVER
1 M A 79 Y Y Y
2 M A 87 Y Y Y
3 F B 65 N N Y
4 F A 58 Y N N
5 F B 72 N N N
6 M B 95 N N Y
7 M C 76 N Y Y
8 F B 56 N Y N
9 M A 77 Y Y N
10 M A 104 N N Y
11 F B 67 N Y N
12 F B 82 Y Y N
13 F B 59 N N N
14 M A 68 Y N N
15 M C 79 N Y Y
16 M B 125 Y N Y
17 F B 83 N N N
18 F A 63 Y N N
19 M C 57 N N Y
20 M A 84 Y N Y
21 M A 72 Y Y Y
22 F B 68 N N Y
23 F C 65 N N N
24 F B 64 N N Y
25 M B 87 Y N Y
26 M B 92 N Y Y
27 F C 56 Y N Y

Let’s use the aggregate command to obtain a table of mean body mass across the two levels of gender. Note the syntax. The continuous variable becomes the first argument. Then the categorical variable appears inside the list command. Finally, the function you wish to apply (in this case you want the mean) becomes the third argument.

Table1 <- aggregate(MASS, list(GENDER), FUN=mean)
Table1

Group.1 x
1 F 66.00000
2 M 84.42857

Note that the aggregate command does not return the variable names. Anyway – now we use the aggregate command to obtain a table of mean body mass across the two levels of smoker (i.e. people who smoke and people who do not).

Table2 <- aggregate(MASS, list(SMOKE), FUN=mean)
Table2

Group.1 x
1 N 73.46667
2 Y 78.16667

The aggregate command allows us to create more complex tables, across the levels of several categorical variables.

Table3 <- aggregate(MASS, list(GENDER, TREATMENT),FUN=mean)
Table3

Group.1 Group.2 x
1 F A 60.50000
2 M A 81.57143
3 F B 68.44444
4 M B 99.75000
5 F C 60.50000
6 M C 70.66667

Finally, let’s look at maximum body mass across the levels of gender, smoker and treatment.

Table4 <- aggregate(MASS, list(GENDER, SMOKE, TREATMENT),FUN=max)
Table4

Group.1 Group.2 Group.3 x
1 M N A 104
2 F Y A 63
3 M Y A 87
4 F N B 83
5 M N B 95
6 F Y B 82
7 M Y B 125
8 F N C 65
9 M N C 79
10 F Y C 56

That wasn’t so hard!

About the Author: David Lillis has taught R to many researchers and statisticians. His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R. David holds a doctorate in applied statistics.

Bookmark and Share

Tagged With: aggregate, R

Related Posts

  • Member Training: What’s the Best Statistical Package for You?
  • The Advantages of RStudio
  • What Really Makes R So Hard to Learn?
  • R is Not So Hard! A Tutorial, Part 22: Creating and Customizing Scatter Plots

Reader Interactions

Comments

  1. Matt says

    December 11, 2018 at 7:31 pm

    In this example, how is the data used by aggregate command called forth (in this example “patients”)? In the aggregate() command there is no argument for data=patients. As expected, this doesn’t work when I try it.

    Reply
    • N says

      May 16, 2020 at 11:51 pm

      Use the structure dataset$column, for example patients$MASS.

      Make sure to use it for each variable, for example:
      aggregate(patients$MASS, list(patients$GENDER), FUN=mean)

      Reply
  2. JFS says

    February 1, 2017 at 5:33 pm

    Hm, reading the table in, so that it shows up, does not add up to functionality.

    Here’s cut-and-paste:

    > read.table(“patients.txt”)
    GENDER TREATMENT MASS SMOKE EXERCISE RECOVER
    1 M A 79 Y Y Y
    2 M A 87 Y Y Y
    3 F B 65 N N Y
    4 F A 58 Y N N
    5 F B 72 N N N
    6 M B 95 N N Y
    7 M C 76 N Y Y
    8 F B 56 N Y N
    9 M A 77 Y Y N
    10 M A 104 N N Y
    11 F B 67 N Y N
    12 F B 82 Y Y N
    13 F B 59 N N N
    14 M A 68 Y N N
    15 M C 79 N Y Y
    16 M B 125 Y N Y
    17 F B 83 N N N
    18 F A 63 Y N N
    19 M C 57 N N Y
    20 M A 84 Y N Y
    21 M A 72 Y Y Y
    22 F B 68 N N Y
    23 F C 65 N N N
    24 F B 64 N N Y
    25 M B 87 Y N Y
    26 M B 92 N Y Y
    27 F C 56 Y N Y
    > Table1 <- aggregate(MASS, list(GENDER), FUN=mean)
    Error in aggregate(MASS, list(GENDER), FUN = mean) :
    object 'MASS' not found

    Reply
  3. JFS says

    February 1, 2017 at 2:13 pm

    Got it to work, but not trivial on a mac if not using a terminal; here are the steps I used.

    1. opened textedit, pasted the table into textedit.

    2. saved as RTF (the current most basic option, there is no longer a .txt save option).

    3. changed the file extension to .txt manually, clicking the “OK” on the warning.

    4. re-opened, highlighted and used the “make plain text” command (doodle-shift-T, or under “format”).

    note, if you “make plain” before the first save, you do get many plain text unicode file saving options…but not knowing what to use, I took the long way around, and let the machine decide.

    5. made a file under “Users” and [the folder with my username] called “Rfiles” and in that file made “DataFiles” and moved the text file there.

    6. at the prompt used
    > getwd ()

    this told me I was in Users/[the folder with my username]

    7. used setwd in two steps (it was being balky when I tried to set the path otherwise) and checked it after each step. namely,

    >setwd(“Rfiles”)
    >getwd()
    [here it gave me output confirming I was in Rfiles]

    >setwd(“DataFiles”)
    >getwd()
    [here it gave me output confirming I was in DataFiles]

    8. finally read in the table, remembering to use the quotation marks
    >read.table(“patients.txt”)

    It then reads in and displays the table as it should.

    There are no doubt faster ways, but several that I tried did not work.

    Reply
  4. Peter Versteegen says

    August 30, 2014 at 2:09 am

    You show the content of “patients”, but you don’t shown how that is obtained.
    Is this a default set in R?

    Reply
    • Jane Rienks says

      September 9, 2014 at 1:09 am

      Save the data in a text file, then use read.table:

      E.g. (remembering to use forward slash or double-back slash)
      datapath<-"C:\\Users\\…..\\R files\\data files\\patients.txt"
      patients<-read.table(datapath, sep="", header=T, as.is=T)

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Please note that, due to the large number of comments submitted, any questions on problems related to a personal study/project will not be answered. We suggest joining Statistically Speaking, where you have access to a private forum and more resources 24/7.

Primary Sidebar

Free Webinars

Binary, Ordinal, and Multinomial Logistic Regression for Categorical Outcomes (Signup)

This Month’s Statistically Speaking Live Training

  • April Member Training: Statistical Contrasts

Upcoming Workshops

  • Logistic Regression for Binary, Ordinal, and Multinomial Outcomes (May 2021)
  • Introduction to Generalized Linear Mixed Models (May 2021)

Read Our Book



Data Analysis with SPSS
(4th Edition)

by Stephen Sweet and
Karen Grace-Martin

Statistical Resources by Topic

  • Fundamental Statistics
  • Effect Size Statistics, Power, and Sample Size Calculations
  • Analysis of Variance and Covariance
  • Linear Regression
  • Complex Surveys & Sampling
  • Count Regression Models
  • Logistic Regression
  • Missing Data
  • Mixed and Multilevel Models
  • Principal Component Analysis and Factor Analysis
  • Structural Equation Modeling
  • Survival Analysis and Event History Analysis
  • Data Analysis Practice and Skills
  • R
  • SPSS
  • Stata

Copyright © 2008–2021 The Analysis Factor, LLC. All rights reserved.
877-272-8096   Contact Us

The Analysis Factor uses cookies to ensure that we give you the best experience of our website. If you continue we assume that you consent to receive cookies on all websites from The Analysis Factor.
Continue Privacy Policy
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

SAVE & ACCEPT