Pivot tables in R – pivoting rows to columns
Pivoting rows to columns – How to pivot a categorical attribute column into columns in R
in this short tutorial we’ll see how pivot rows to columns in R – replicating moving a categorical attribute from a pivot table row to a pivot table column (as you would do it in Excel).
follow the step by step below in R studio or download the R file from github.
# clean up the environment
rm(list = ls())
# we’ll need dplyr and tidyr for this, by far easier than with base R
# read in the Canadian SuperStore dataset from this dropbox address:
df <- read.csv(“https://www.dropbox.com/s/kj9yioc24iq4pdb/superstore.csv?dl=1”)
Let’s have a quick look in the excel:
# in a previous tutorial we created a summary table with this dplyr code, summarising
# sales by product category, region and customer segment:
pivot2 <- df %>%
select(Product.Category, Region, Customer.Segment, Sales) %>%
group_by(Product.Category, Region, Customer.Segment) %>%
summarise(TotalSales = sum(Sales))
# let’s emulate an Excel pivoting and pivot rows to columns in R, by spreading out the regions to
# seperate columns.
# we use the TidyR “spread” function to summarize the region in columns: