gather with multiple keys

10,131

Solution 1

The following works:

df %>% gather(Year, Value, -Precinct, -Crime)

Solution 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)
Share:
10,131

Related videos on Youtube

DataScienceAmateur
Author by

DataScienceAmateur

Updated on September 15, 2022

Comments

  • DataScienceAmateur
    DataScienceAmateur over 1 year

    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.

    • akrun
      akrun about 7 years
      Just use gather(df1, Year, Value, 3:ncol(df1))
  • Daniel
    Daniel about 7 years
    Damn, I was too slow!
  • Sotos
    Sotos about 7 years
    yes. No point in keeping it right?
  • Konrad Rudolph
    Konrad Rudolph about 7 years
    Bizarre: why was this perfectly working, best-practice answer downvoted?