简体   繁体   English

倒计时R

[英]Countdown dates in R

Suppose I have the following dataset:假设我有以下数据集:

id1 <- c(1,1,1,1,2,2,2,2,1,1,1,1)
dates <- c("a","a","a","a","b","b","b","b","c","c","c","c")
x <- c(NA,0,NA,NA,NA,NA,0,NA,NA,NA,NA,0)

df <- data.frame(id1,dates,x)

My objective is to have a new column that explicitly tells counts the sequence of observations around 0 for every combination of id1 and dates.我的目标是有一个新列,明确告诉计数 id1 和日期的每个组合的 0 附近的观察序列。 This would yield the following outcome:这将产生以下结果:

desired_result <- c(-1,0,1,2,-2,-1,0,1,-3,-2,-1,0)

Any help is appreciated.任何帮助表示赞赏。

library(dplyr)
df %>% 
  group_by(id1, dates) %>% 
  mutate(x = row_number() - which(x == 0))
     id1 dates     x
 1     1 a        -1
 2     1 a         0
 3     1 a         1
 4     1 a         2
 5     2 b        -2
 6     2 b        -1
 7     2 b         0
 8     2 b         1
 9     1 c        -3
10     1 c        -2
11     1 c        -1
12     1 c         0

With dplyr 1.1.0 :使用dplyr 1.1.0

df %>% 
  mutate(x = row_number() - which(x == 0), .by = dates)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM