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

如何创建记录person_id出现次数的visit_occurrance列?

解决方案

要给数据框新增Visit_occurrance列,统计每个Person_ID的出现次数(按原有行顺序依次计数),可以用以下两种常用方法:

方法一:使用dplyr包(tidyverse风格)

先加载dplyr包,按Person_ID分组后,用row_number()生成组内序号:

library(dplyr)

df <- df %>%
  group_by(Person_ID) %>%
  mutate(Visit_occurrance = row_number()) %>%
  ungroup()

运行后验证结果:

dput(df)
# 输出结构与你期望的一致

方法二:使用Base R(无需额外安装包)

借助ave()函数结合seq_along实现分组计数:

df$Visit_occurrance <- ave(df$Person_ID, df$Person_ID, FUN = seq_along)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:45:20