pivot wider so that grouped variables appear as subheaders in table in r

To pivot wider and have grouped variables appear as subheaders in a table in R, you can use the pivot_wider function from the tidyr package in combination with dplyr for data manipulation. Here's an example:

main.r
# Install and load required packages
install.packages(c("tidyr", "dplyr"))
library(tidyr)
library(dplyr)

# Create a sample dataset
dataset <- data.frame(
  id = c(1, 1, 1, 2, 2, 2),
  year = c(2018, 2019, 2020, 2018, 2019, 2020),
  sales = c(100, 120, 150, 200, 220, 250),
  expenses = c(50, 60, 70, 80, 90, 100)
)

# Pivot wider
pivoted_data <- dataset %>%
  pivot_wider(
    id_cols = id,
    names_from = year,
    values_from = c(sales, expenses)
  )

# Print the pivoted data
print(pivoted_data)
502 chars
24 lines

In this example, id is the column that we group by, year is the column that we pivot on, and sales and expenses are the columns that we want to pivot wider. The resulting table will have subheaders for each year and sales/expenses combination.

Note: Make sure to replace dataset with your actual dataset and adjust the id_cols, names_from, and values_from arguments according to your data.

Alternatively, you can use reshape function from base R, but pivot_wider from tidyr is generally easier to use and more flexible.

Output will look something like this:

main.r
# A tibble: 2 x 7
     id sales_2018 sales_2019 sales_2020 expenses_2018 expenses_2019 expenses_2020
  <dbl>       <dbl>       <dbl>       <dbl>         <dbl>         <dbl>         <dbl>
1     1         100         120         150            50            60            70
2     2         200         220         250            80            90           100
359 chars
6 lines

related categories

gistlibby LogSnag