R如何识别最后一次发生的距离 [英] R how to identify distance of last occurance

查看:116
本文介绍了R如何识别最后一次发生的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算自从发生以来的时间。

I want to calculate how long its been since something occurred.

下面的例子可以看到,指示灯在某些时间点亮,但不是全部的时间。

Given the following, you can see that the light is on some of the time, but not all of the time. I want to normalize the data to feed it to a neural network.

library(data.table)
d<-data.table(
    date = c("6/1/2013", "6/2/2013","6/3/2013","6/4/2013"),
    light = c(TRUE,FALSE,FALSE,TRUE) 
)
d
       date light
1: 6/1/2013  TRUE
2: 6/2/2013 FALSE
3: 6/3/2013 FALSE
4: 6/4/2013  TRUE


$ b b

我想计算的是另一列显示上一次出现的距离。

what I'd like to calculate is another column that shows the "distance" to the last occurrence.

所以上面的数据:
第一行,因为它应该为零
第二行,应为1
第三行,应为2
第四行,应为零

so for the data above: first row, since its on it should be zero second row, should be 1 third row, should be 2 fourth row, should be zero

任何帮助都非常感激。

推荐答案

b $ b

d[, distance := 1:.N - 1, by = cumsum(light)]

或:

d[, distance := .I - .I[1], by = cumsum(light)]

的天而不是行距,你可以使用:

And if you want to actually count number of days as opposed to row-distance, you could use:

d[, distance := as.numeric(as.POSIXct(date, format = "%m/%d/%Y") -
                           as.POSIXct(date[1], format = "%m/%d/%Y"),
                           units = 'days'),
    by = cumsum(light)]

这篇关于R如何识别最后一次发生的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆