Percent of total, pivot table “show values as” in R

Posted on: October 16, 2017 Posted by: Guy Manova Comments: 0

Percent of total, pivot table “show values as” in R

mimicking “show value as” in R, as well as generally doing percent of total in R

This is a short tutorial on how you can mimic Excel’s pivot table “show value as” functionality, as well as generally showing how to create a proportion table (prop table) to compute percent of total in R:

# pre-session options

rm(list = ls())
# getwd()
# setwd(“C:/Users/your preferred path”)

# load tidyr for pivoting:


df <- read.csv(url(“”),
skip = 0,
header = TRUE,
stringsAsFactors = 0)

write.csv(df, “proptable.csv”)

# in Excel:


# in R:

# first, create a pivot table:

df <- df %>%
spread(OS, Installs)

# then create a prop table (proportion table) on rows (1) or on columns (2)
# VERY IMPORTANT! this only works on MATRICES, so you need to subset the table
# so only numeric columns will be in the subset!

df.prop.rows <- prop.table(as.matrix(df[,2:3]),1)


# now, let’s re-attach the country names:

df.prop.rows <-“Country”=df[,1],df.prop.rows)


# let’s have a look at columns:

df.prop.cols <- prop.table(as.matrix(df[,2:3]),2)

df.prop.cols <-“Country”=df[,1],df.prop.cols)


# check your totals to see indeed amounts to 100%


Leave a Reply:

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