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

如何在R语言中按年份生成表示配对出现次数的数值变量?

生成whatiwant变量的解决方案

从你提供的示例数据来看,whatiwant的逻辑是:对每一组exporter+product的组合,按year从小到大标记该组合的出现序号(第1次出现记1,第2次记2)。add_count()会直接返回组合的总出现次数,无法实现这种逐行累计的序号需求,以下是可行的实现方法:

方法一:使用dplyr(tidyverse)

先按年份排序,再按exporter和product分组,最后生成组内的累计序号:

library(dplyr)

# 假设原始df3不含whatiwant变量(即df1、df2先去掉whatiwant再合并)
df3 <- df3 %>%
  arrange(year) %>%
  group_by(exporter, product) %>%
  mutate(whatiwant = row_number()) %>%
  ungroup()

方法二:使用base R

通过ave()函数结合排序操作,实现分组序号生成:

# 先按年份排序数据
df3 <- df3[order(df3$year), ]
# 生成whatiwant变量
df3$whatiwant <- ave(rep(1, nrow(df3)), df3$exporter, df3$product, FUN = seq_along)

运行上述任意一种方法后,df3的whatiwant列都会和你示例中的结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:20