0

I need to reshape a dataframe from long to wide. I want to reshape several variables but also maintain the format of the rest of the dataframe. I have a dataframe that has the race, quintile and income for several years.

df <- structure(list(year = c(2019, 2019, 2019, 2018, 2018, 2018), race = c("Black Alone","Black Alone", "Black Alone", "Black Alone", "Black Alone", "Black Alone"), quintile = c("Lowest", "Middle", "Highest", "Lowest", "Middle", "Highest"), income = c(8680, 45356, 177659, 7657, 42202, 155520)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

The dataframe dfis shown below:

year  race         quintile  income
2019  Black Alone  Lowest    8680
2019  Black Alone  Middle    45356
2019  Black Alone  Highest   177659
2018  Black Alone  Lowest    7657
2018  Black Alone  Middle    42202
2018  Black Alone  Highest   155520

I want the dataframe instead to look like:

year  race         Lowest_income  Middle_income  Highest_income
2019  Black Alone  8680           45356          177659
2018  Black Alone  7657           42202          155520

I'm not sure where to start to accomplish this. Any help would be appreciated!

1 Answers1

1

We can use

library(dplyr)
library(tidyr)
library(stringr)
df %>% 
   mutate(quintile = str_c(quintile, '_income')) %>%
   pivot_wider(names_from = 'quintile', values_from = income)

-output

# A tibble: 2 x 5
#   year race        Lowest_income Middle_income Highest_income
#  <dbl> <chr>               <dbl>         <dbl>          <dbl>
#1  2019 Black Alone          8680         45356         177659
#2  2018 Black Alone          7657         42202         155520
akrun
  • 874,273
  • 37
  • 540
  • 662