-1

enter image description here

Hello guys, I have a data frame with the columns "Auto", "ClasPri" and "Total". For each "Auto" I can have 4 different "ClasPri" and a "Total" for each "ClasPri". I wanted to make each "Auto" appear only once and the other columns to be "0, 1, 2, 3" with their respective "Total". Can someone help me? The first image is as it is and the second as it should be.

The first image is how it is and the second is how I wanted it to look

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Please add data using `dput` and not as images. Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Jul 19 '20 at 01:38
  • Try `xtabs(Total~Auto+ClasPri)`. – dcarlson Jul 19 '20 at 02:42

1 Answers1

1

I think you're just trying to pivot your data on ClasPri. Here's a dplyr / tidyr way to do that:

library(tidyr)
library(dplyr)

arrange(df, ClasPri) %>%
  pivot_wider(names_from = ClasPri, values_from = Total, values_fill = 0) %>%
  arrange(Auto)
#> # A tibble: 4 x 5
#>    Auto   `0`      `1`     `2`     `3`
#>   <int> <int>    <int>   <int>   <int>
#> 1   343     0   688160 8260000       0
#> 2   453  6000 29168829 7663334 2275200
#> 3   469     0  7888857       0  540000
#> 4   609     0        0       0       0

Data used

df <- data.frame(Auto    = c(343L, 343L, 453L, 453L, 453L, 453L, 469L, 469L, 609L), 
                 ClasPri = c(1L, 2L, 0L, 1L, 2L, 3L, 1L, 3L, 1L), 
                 Total   = c(688160L, 8260000L, 6000L, 29168829L, 
                             7663334L, 2275200L, 7888857L, 540000L, 0L))

df
#>   Auto ClasPri    Total
#> 1  343       1   688160
#> 2  343       2  8260000
#> 3  453       0     6000
#> 4  453       1 29168829
#> 5  453       2  7663334
#> 6  453       3  2275200
#> 7  469       1  7888857
#> 8  469       3   540000
#> 9  609       1        0

Created on 2020-07-19 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87