R如何识别最后一次出现的距离 [英] R how to identify distance of last occurrence

查看:66
本文介绍了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

我想计算的是另一列,它显示了到最后一次出现的距离。

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

推荐答案

应该这样做:

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天全站免登陆