【发布时间】:2019-10-09 15:09:33
【问题描述】:
我在 R 中有一个数据表,看起来像:
city year target
1: NYC 2000 0
2: NYC 2000 1
3: NYC 2000 1
4: LA 2000 0
5: LA 2000 0
6: LA 2000 1
7: LA 2000 1
可以通过以下方式创建:
data = data.table(city = c("NYC", "NYC", "NYC", "LA", "LA", "LA", "LA"),
year = c(2000, 2000, 2000, 2000, 2000, 2000, 2000),
target = c(0, 1, 1, 0, 0, 1, 1))
我想按city 和year 对它们进行分组,并在target列中找到第一个非零元素的索引,这样我就可以对其进行修改,所需的结果应该如下所示:
city year target
1: NYC 2000 0
2: NYC 2000 666
3: NYC 2000 1
4: LA 2000 0
5: LA 2000 0
6: LA 2000 666
7: LA 2000 1
感谢任何帮助。
以下不起作用:
cutoff_thresh <- function(x, cutoff) {x > cutoff}
helper <- data %>%
group_by(city, year) %>%
mutate(thresh = detect_index(.x = target,
.f = cutoff_thresh,
cutoff = 0)
)
它产生给定年份中第一个非零元素出现的确切日期,
它从每年的第一天开始计算。因此,如果 2000 有 365 天,并且 2001 的第二天我们是非零的,它返回 2 代表 (NYC, 2001) 而不是 365 + 2。不足为奇!
【问题讨论】:
标签: r group-by dplyr data.table