Summarizing Data in R

April 10, 2013
By

(This article was first published on Mathew Analytics » R, and kindly contributed to R-bloggers)

When work with large amounts of data that is structured in a tabular format, a common operation is to summarize that data in different ways using specific variables. In Microsoft Excel, pivot tables are a nice feature that is used for this purpose. Of course, R also has similar calculations that can be used to summarize large amount of data. In the following R code, I utilizeR to summarize a data frame by specific variables.

## DATA

dat = data.frame(
  name=c("Tony","James","Sara","Alice","David","Angie","Don","Faith","Becky","Jenny"),
   state=c("KS","IA","CA","FL","MI","CO","KA","CO","KS","CA"),
   gender=c("M","M","F","F","F","M","F","M","F","F"),
   marital_status=c("M","S","S","S","M","M","S","M","S","M"),
   credit=c("good","good","poor","fair","poor","fair","fair","fair","good","fair"),
   owns_home=c(0,1,0,0,1,0,1,1,1,1),
   cost=c(500,200,300,150,200,300,400,450,250,150))

dat  

## DDPLY FUNCTION IN THE PLYR PACKAGE 
## Use 'nrow' to find the count of a particular variable  
library(plyr)
ddply(dat, .(credit), "nrow")
ddply(dat, .(gender), "nrow")
ddply(dat, .(marital_status, credit), "nrow")
## use 'summarise' to summarize numeric variables
ddply(dat, .(gender), summarise, mean_cost = mean(cost))
ddply(dat, .(state), summarise, mean_cost = mean(cost))
ddply(dat, .(gender), summarise, min_cost = min(cost), 
      max_cost = max(cost), mean_cost = mean(cost))
ddply(dat, .(gender, credit), summarise, credit=length(credit),
      min_cost = min(cost), max_cost = max(cost), mean_cost = mean(cost))

## AGGREGATE FUNCTION FROM BASE R
aggregate(cost ~ marital_status + gender, data=dat, FUN=mean)
aggregate(cost ~ credit + gender, data=dat, FUN=mean)

To leave a comment for the author, please follow the link and comment on their blog: Mathew Analytics » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Mango solutions



plotly webpage

dominolab webpage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training

datasociety

http://www.eoda.de





ODSC

ODSC

CRC R books series





Six Sigma Online Training









Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)