Expand ranges defined by “from” and “to” columns

前端 未结 9 1732
悲哀的现实
悲哀的现实 2020-11-22 07:02

I have a data frame containing \"name\" of U.S. Presidents, the years when they start and end in office, (\"from\" and \"to\" columns

9条回答
  •  难免孤独
    2020-11-22 07:29

    An alternate tidyverse approach using unnest and map2.

    library(tidyverse)
    
    presidents %>%
      unnest(year = map2(from, to, seq)) %>%
      select(-from, -to)
    
    #              name  year
    # 1    Bill Clinton  1993
    # 2    Bill Clinton  1994
    ...
    # 21   Barack Obama  2011
    # 22   Barack Obama  2012
    

    Edit: From tidyr v1.0.0 new variables can no longer be created as part of unnest().

    presidents %>%
      mutate(year = map2(from, to, seq)) %>%
      unnest(year) %>%
      select(-from, -to)
    

提交回复
热议问题