You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于访问记录创建标识调查周期的变量

问题描述

现有一个数据框,已有的R代码可根据各站点到访日期生成访问次数列n_visit——当两次访问间隔超过3天时,计数会重新开始。现需新增一列名为survey_period的字段,用于标识该计数周期所属的调查阶段。

示例:站点wood_lab_pond在2023-05-03、2023-05-15、2023-05-16的访问记录中,2023-05-03对应的survey_period为1,2023-05-15和2023-05-16对应的survey_period为2。

期望输出示例

sitedaten_visitsurvey_period
wood_lab_pond2023-05-03visit_11
wood_lab_pond2023-05-15visit_12
wood_lab_pond2023-05-16visit_22

现有代码

ndays <- 3

data <- raw_data%>% 
  mutate(near = (lag(date, default = first(date)) + ndays < date) |> cumsum(), 
         .by = site) %>%  
  mutate(n_visit = rep(list(1,2,3), length.out = n()), .by = c(site, near),
         n_visit = paste("visit_", n_visit, sep=""))

原始数据结构

raw_data <- structure(list(site = c("tryon_weber", "phelps_pond", "phelps_pond", 
"admin_pond", "wood_lab_pond", "admin_pond", "phelps_pond", "wood_lab_pond", 
"wood_lab_pond", "rv_pond", "rv_pond", "rv_pond", "tuttle_pond", 
"tuttle_pond", "vorisek_pond", "tuttle_pond", "vorisek_pond", 
"vorisek_pond", "rv_pond", "tryon_weber", "tryon_weber", "rv_pond", 
"tryon_weber", "rv_pond"), date = structure(c(19447, 19447, 19452, 
19467, 19480, 19487, 19488, 19492, 19493, 19499, 19500, 19501, 
19506, 19507, 19507, 19508, 19508, 19509, 19513, 19513, 19514, 
19514, 19515, 19515), class = "Date")), class = "data.frame", row.names = c(NA, 
-24L))

内容的提问来源于stack exchange,提问作者Eizy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:55:27