Search code examples
rif-statementdata.tabledata-manipulationreplicate

R use ifelse to replicate


I want to use ifelse to replicate my data.
The problem is How to use ifelse to replicate different rows, which have different conditions. Or maybe there are other solutions. data here:

type     Time          value
A        2015-01-01    100
A        2016-05-01    200
B        2015-12-01    150
B        2016-12-01    300

The result I want is like:

type     Time          value
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2015-01-01    100
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
A        2016-05-01    200
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150
B        2015-12-01    150    
B        2016-12-01    300

My code:

library(readxl)
library(lubridate)
library(data.table)
data <- read_excel("data.xlsx")
data <- as.data.table(data)
data[,Time:=as.Date(Time,"%Y/%m/%d")]
result <- data[ifelse(year(Time)==2016,rep(1:.N,12-month(Time)+1),rep(1:.N,13))]

However, it is not the same as what I actually want.
I think the problem is I cannot use .N. Any suggestion? Thanks.


Solution

  • You can create a reps column based on your conditions, that will allow us to repeat each row times the value in this new variable:

    library(data.table)
    data[,reps:=ifelse(year(Time)==2016, 12-month(Time)+1, 13)][rep(1:.N,reps)]
    

    Or without ifelse():

    data[,reps := 13][year(Time)==2016, reps := 11-month(Time)][rep(1:.N, reps)]