5

I know this question has been asked before, but I don't quite understand.

I have a dataset that looks like this:

Precinct  Crime       2000   2001  2002  2003  
1         Murder       3      1     2     2
1         Rape         12     5     10    11
1         Burglary     252   188    297   403
2         Murder       4      2      1     0 

with the values of each crime listed under the year.

I'm trying to rearrange it into simpler sets that look like this:

Precinct    Crime    Year   Value
   1        Murder   2000     3
   1        Rape     2000     12

How do I go about doing that? I know I should be using tidyr's gather, but extrapolating solutions for multiple keys isn't working for me.

Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
DataScienceAmateur
  • 168
  • 1
  • 3
  • 11
  • 1
    Just use `gather(df1, Year, Value, 3:ncol(df1))` – akrun Jan 27 '17 at 15:19
  • > exact duplicate of an existing question This is not exactly the same if worded differently. It is actually the opposite. He wasn't to go from a wide format to a wide format. Which can be done with tiddy:gather. – mtelesha Nov 16 '17 at 17:38

2 Answers2

10

The following works:

df %>% gather(Year, Value, -Precinct, -Crime)
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
1

You need to specify all columns that should be gathers (or remove all columns that should _not_be gathered):

library(tidyverse)

dat <- tibble::tibble(
  Precinct = c(1, 1, 1, 2),
  Crime = c("Murder", "Rape", "Burglary", "Murder"),
  `2000` = c(3, 12, 252, 4),
  `2001` = c(1, 5, 188, 2),
  `2002` = c(2, 10, 297, 1),
  `2003` = c(2, 11, 403, 0)
)

tidyr::gather(dat, Year, Value, 3:6)
tidyr::gather(dat, Year, Value, -Precinct, -Crime)
Daniel
  • 6,454
  • 5
  • 21
  • 35