r - Expand data.frame into distinct rows -
this question has answer here:
- r creating sequence table 2 columns 4 answers
i trying figure out how can expand data.frame in r distinct rows. this, mean using startyear , toyear variables create annual data.frame id replicated each distinct year in sequence from=startyear to=endyear.
i have example data.frame:
testdat <- data.frame(id=seq(1,10), startyear=c(1946,1960,1965,1976,1955,1999,2013,1981,1983,1995) ) testdat$endyear <- testdat$startyear+sample(1:10,10,replace=true)
this creates:
id startyear endyear 1 1 1946 1951 2 2 1960 1966 3 3 1965 1969 . . .... ....
what desired result this:
id year 1 1946 1 1947 1 1948 1 1949 1 1950 1 1951 2 1960 . ....
any advice on how great. thanks.
try "hadley'verse", namely dplyr
, tidyr
:
library(dplyr) library(tidyr) testdat %>% group_by(id) %>% expand(year=full_seq(c(startyear, endyear), 1)) # source: local data frame [64 x 2] # groups: id [10] # # id year # (int) (dbl) # 1 1 1946 # 2 1 1947 # 3 1 1948 # 4 1 1949 # 5 1 1950 # 6 1 1951 # 7 1 1952 # 8 2 1960 # 9 2 1961 # 10 3 1965 # .. ... ...