![](/img/trans.png)
[英]R: How to flag observations within a certain timeframe in data.table?
[英]Quick way to identify observations that meets certain criteria in data.table
library('data.table')
set.seed(1)
A<-data.table(age = rnorm(10, mean = 10), V1= rnorm(10))
情況是我想在data.table
A中創建一個新列,對於每個觀察,它將查找年齡差距在0.5到1年之間的任何觀察,並使用該觀察值的V1
作為V2
為當前觀察。 如果有多個觀察結果符合標准,只需確定最接近0.5年差距的觀察結果。
我想知道是否有一種快速的方法來實現data.table而不使用for
循環。
它可能......而且很有趣......但不是那么漂亮,也不可讀:
CJ(A1=A$age,A2=A$age)[,.(A1, A2,d=abs(A1-A2))
][d>=0.5 & d<=1
][, .(d, dmin=min(d),A2), by="A1"
][d==dmin
][A, .(A1, A2,V2=i.V1,d), on=c(A2="age"), nomatch=0
][A, .(age=A1, A2, V1, d, V2), on=c(A1="age")]
age A2 V1 d V2
1: 9.373546 10.183643 1.51178117 0.8100971 0.38984324
2: 10.183643 10.738325 0.38984324 0.5546814 0.94383621
3: 9.164371 9.694612 -0.62124058 0.5302402 0.59390132
4: 11.595281 10.738325 -2.21469989 0.8569561 0.94383621
5: 10.329508 9.694612 1.12493092 0.6348962 0.59390132
6: 9.179532 9.694612 -0.04493361 0.5150800 0.59390132
7: 10.487429 9.694612 -0.01619026 0.7928174 0.59390132
8: 10.738325 10.183643 0.94383621 0.5546814 0.38984324
9: 10.575781 9.694612 0.82122120 0.8811697 0.59390132
10: 9.694612 9.179532 0.59390132 0.5150800 -0.04493361
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.