0

I have a data that looks like this:

enter image description here

and I would like to summarise the data into multi-level rows and columns and I would like to make it look like this

enter image description here

I was successful in creating multi-level rows but could not put the price_flag in columns. I used the below mentioned code to do that

aggregate(data$year, by = list(data$class, data$year), FUN = length)

Help would be deeply appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • You will get much happier and quicker help if you provide sample input in valid R syntax - `dput()` is a great function for sharing a copy/pastable version of an R object. And what do you want to go in all those blanks? – Gregor Thomas Jun 18 '18 at 18:45
  • 1
    Possible duplicate of [R: How to spread, group\_by, summarise and mutate at the same time](https://stackoverflow.com/questions/44687455/r-how-to-spread-group-by-summarise-and-mutate-at-the-same-time) – CPak Jun 18 '18 at 18:51

1 Answers1

0
dat
   ID price_flag Year Class
1 123     5k-10k 2016     A
2 234    10k-25k 2017     B
3 345    25k-50k 2018     C
4 456     5k-10k 2017     A
5 567    10k-25k 2018     C

ftable(rev(dat[-1]))
           price_flag 10k-25k 25k-50k 5k-10k
Class Year                                  
A     2016                  0       0      1
      2017                  0       0      1
      2018                  0       0      0
B     2016                  0       0      0
      2017                  1       0      0
      2018                  0       0      0
C     2016                  0       0      0
      2017                  0       0      0
      2018                  1       1      0

or even:

ftable(dat[4:2])
           price_flag 10k-25k 25k-50k 5k-10k
Class Year                                  
A     2016                  0       0      1
      2017                  0       0      1
      2018                  0       0      0
B     2016                  0       0      0
      2017                  1       0      0
      2018                  0       0      0
C     2016                  0       0      0
      2017                  0       0      0
      2018                  1       1      0
Onyambu
  • 67,392
  • 3
  • 24
  • 53