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.