Home > Mobile >  How to create subsequent data based on the first row?
How to create subsequent data based on the first row?

Time:04-15

I want to generate subsequent data based on the first row of data, how to do it. I did it using a for loop, but it's too slow. Like this. The initial dataframe is:

DataORI <- tibble(
  Year = c(2010:2015),
  Age = rep(60,length(c(2010:2015))),
  Wage = rep(1000,length(c(2010:2015)))
)
Year  Age  Wage
2010  60   1000
2011  60   1000
2012  60   1000

My goal is:

Year  Age  Wage
2010  60   1000
2011  61   1000
2012  62   1000
2011  60   1000
2012  61   1000
2013  62   1000
2012  60   1000
2013  61   1000
2014  62   1000

Of course, my data has longer years and ages and more columns. How to do it to improve efficiency.

CodePudding user response:

We may use crossing

library(dplyr)
library(tidyr)
DataORI %>% 
   select(-Age) %>%
   crossing(Age = 60:62)
  •  Tags:  
  • r
  • Related