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.
The following works:
df %>% gather(Year, Value, -Precinct, -Crime)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With