Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gather with multiple keys [duplicate]

Tags:

r

transpose

tidyr

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.

like image 859
DataScienceAmateur Avatar asked Jan 27 '17 15:01

DataScienceAmateur


Video Answer


2 Answers

The following works:

df %>% gather(Year, Value, -Precinct, -Crime)
like image 103
Konrad Rudolph Avatar answered Oct 07 '22 15:10

Konrad Rudolph


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)
like image 26
Daniel Avatar answered Oct 07 '22 14:10

Daniel