gather with multiple keys [duplicate]
Asked Answered
D

2

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.

Decorticate answered 27/1, 2017 at 15:14 Comment(2)
Just use gather(df1, Year, Value, 3:ncol(df1))Grudge
> 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.Lumbye
T
11

The following works:

df %>% gather(Year, Value, -Precinct, -Crime)
Taxable answered 27/1, 2017 at 15:19 Comment(1)
Bizarre: why was this perfectly working, best-practice answer downvoted?Taxable
F
2

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)
Fledgy answered 27/1, 2017 at 15:22 Comment(2)
Damn, I was too slow!Fledgy
yes. No point in keeping it right?Burgos

© 2022 - 2024 — McMap. All rights reserved.