-1

How do I transform data from multiple rows per year

Year type N
1    1    10
1    2    20
2    1    10
2    2    10

to one row per year with multiple columns

Year type1 type2 total
1    10     20    30
2    10     10    20
Wendy
  • 144
  • 9
  • Provide reproducible data and expected ouput nex time. Makes it easier to answer your question and may be the reason for downvote –  Jul 26 '19 at 18:10

1 Answers1

3

An option would be to paste the 'type' string in the type column, spread to. 'wide' format. and then create the 'total' by adding the 'type1' and 'type2' columns

library(tidyverse)
df1 %>%
   mutate(type = str_c("type", type)) %>%
   spread(type, N) %>%
   mutate(total =type1 + type2)
akrun
  • 874,273
  • 37
  • 540
  • 662