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

前端 未结 9 1943
悲哀的现实
悲哀的现实 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:10

    Here's a dplyr solution:

    library(dplyr)
    
    # the data
    presidents <- 
    structure(list(name = c("Bill Clinton", "George W. Bush", "Barack Obama"
    ), from = c(1993, 2001, 2009), to = c(2001, 2009, 2012)), .Names = c("name", 
    "from", "to"), row.names = 42:44, class = "data.frame")
    
    # the expansion of the table
    presidents %>%
        rowwise() %>%
        do(data.frame(name = .$name, year = seq(.$from, .$to, by = 1)))
    
    # the output
    Source: local data frame [22 x 2]
    Groups: 
    
                 name  year
                (chr) (dbl)
    1    Bill Clinton  1993
    2    Bill Clinton  1994
    3    Bill Clinton  1995
    4    Bill Clinton  1996
    5    Bill Clinton  1997
    6    Bill Clinton  1998
    7    Bill Clinton  1999
    8    Bill Clinton  2000
    9    Bill Clinton  2001
    10 George W. Bush  2001
    ..            ...   ...
    

    h/t: https://stackoverflow.com/a/24804470/1036500

提交回复
热议问题