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

前端 未结 9 1929
悲哀的现实
悲哀的现实 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条回答
  •  猫巷女王i
    2020-11-22 07:10

    Another option using tidyverse could be to gather data into long format, group_by name and create a sequence between from and to date.

    library(tidyverse)
    
    presidents %>%
      gather(key, date, -name) %>%
      group_by(name) %>%
      complete(date = seq(date[1], date[2]))%>%
      select(-key) 
    
    # A tibble: 22 x 2
    # Groups:   name [3]
    #   name          date
    #           
    # 1 Barack Obama  2009
    # 2 Barack Obama  2010
    # 3 Barack Obama  2011
    # 4 Barack Obama  2012
    # 5 Bill Clinton  1993
    # 6 Bill Clinton  1994
    # 7 Bill Clinton  1995
    # 8 Bill Clinton  1996
    # 9 Bill Clinton  1997
    #10 Bill Clinton  1998
    # … with 12 more rows
    

提交回复
热议问题