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

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

## 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()

library(tidyr)

skip = 0,
stringsAsFactors = 0)

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

### # in R:

# first, create a pivot table:

df <- df %>%

# 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)

df.prop.rows

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

df.prop.rows <- cbind.data.frame(“Country”=df[,1],df.prop.rows)

df.prop.rows

# let’s have a look at columns:

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

df.prop.cols <- cbind.data.frame(“Country”=df[,1],df.prop.cols)

df.prop.cols

# check your totals to see indeed amounts to 100%

rowSums(df.prop.rows[,2:3])
colSums(df.prop.cols[,2:3])