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

如何优雅实现R语言字符向量中元素的出现顺序编号统计?

解决方案

下面是几种无需手动循环、更优雅的现成方法来实现你的需求:

1. 使用data.table包的rowid函数

这是最简洁的方法之一,rowid函数专门用来按分组生成组内序号:

library(data.table)
crop = c("spring barley", "winter wheat", "potatoe", "spring barley", "alfalfa", "winter wheat", "winter wheat")
id = rowid(crop)
df = data.frame(crop, id)
df

运行后直接得到你想要的结果,rowid会自动为每个crop的重复出现依次编号。

2. 使用dplyr包的分组累加

如果你熟悉tidyverse生态,用dplyr的分组+row_number()也很直观:

library(dplyr)
crop = c("spring barley", "winter wheat", "potatoe", "spring barley", "alfalfa", "winter wheat", "winter wheat")
df = tibble(crop) %>%
  group_by(crop) %>%
  mutate(id = row_number()) %>%
  ungroup()
df

group_by(crop)按作物分组后,row_number()会为每组内的元素生成从1开始的递增序号。

3. 基础R方法(无需额外包)

如果不想加载第三方包,用基础R的ave函数也能实现:

crop = c("spring barley", "winter wheat", "potatoe", "spring barley", "alfalfa", "winter wheat", "winter wheat")
id = ave(rep(1, length(crop)), crop, FUN = cumsum)
df = data.frame(crop, id)
df

ave会对每个crop分组应用cumsum函数,对每组里的重复1累加,自然得到从1开始的序号。

这些方法都比手动循环或者提取make_clean_names后缀更直接,属于专门处理这类组内序号生成的现成方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:50:13