I have a data.table like below and i need to build a V2 column with the (ratio number of (V1[Day+1:Day+7] < value1))
_______date________|_V1__|V2_to_build
row1:2019-01-01_____|.10...| 2/7
row2:2019-01-02_____|...5...| 0/7
row3:2019-01-03_____|.30...| 3/7
row4:2019-01-04_____|.55...|
row5:2019-01-05_____|.21...|
row6:2019-01-06_____|.51...|
row7:2019-01-07_____|.10...|
row8:2019-01-08_____|..8...|
row9:2019-01-09_____|.35...|
row10:2019-01-10____|..4...|
rowZ:2019-01-50_____|.200..|
explanations for 2 first row:
V2[row1]= 2/7 => (5<10 = True ,30<10 = False, 55<10 = False, 21<10 = False, 51<10 = False, 10<10 = False, 8<10 = True)
V2[row2] = 0/7 => (30<5 = False, 55<5 = False, 21<5 = False, 51<5 = False, 10<5 = False, 8< 5 = False)
May you help me 'cause it's painful with my basic skills in R thanks in advance.
You can use the non-equi join from data.table
as follows:
DT[, V2_to_build :=
DT[.(start=date, end=date+7L, val=V1), on=.(date>start, date<=end, V1<val),
allow.cartesian=TRUE,
by=.EACHI, .(V2=.N / 7)]$V2
]
output:
date V1 V2_to_build
1: 2019-01-01 10 0.2857143
2: 2019-01-02 5 0.0000000
3: 2019-01-03 30 0.5714286
4: 2019-01-04 55 0.8571429
5: 2019-01-05 21 0.4285714
6: 2019-01-06 51 0.5714286
7: 2019-01-07 10 0.2857143
8: 2019-01-08 8 0.1428571
9: 2019-01-09 35 0.1428571
10: 2019-01-10 4 0.0000000
data:
DT <- fread("date|V1
2019-01-01|10
2019-01-02|5
2019-01-03|30
2019-01-04|55
2019-01-05|21
2019-01-06|51
2019-01-07|10
2019-01-08|8
2019-01-09|35
2019-01-10|4")
DT[, date := as.Date(date, format="%Y-%m-%d")]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.