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

如何在R中找出多列中重复出现的年月值(含跨列匹配)

解决方案:找出存在多场风暴的年月(含跨列匹配)

核心思路

把所有年月数据(year_month_min和year_month_max)整合到同一列,统计每个年月对应的唯一风暴数量,只要数量≥2,就说明该年月存在至少两场不同风暴——这个逻辑自动覆盖你提出的三个匹配条件,同时排除仅自身行内min/max相同的单风暴情况。

具体代码实现

1. 加载所需工具包

library(dplyr)
library(tidyr)

2. 转换数据格式并筛选目标年月

# 第一步:将宽格式数据转为长格式,收集所有年月与对应风暴
long_data <- my_data %>%
  pivot_longer(
    cols = c(year_month_min, year_month_max),
    names_to = "month_type",
    values_to = "year_month"
  ) %>%
  select(storm_name, year_month) # 保留关键列

# 第二步:统计每个年月的唯一风暴数,筛选出至少2场的年月
target_months <- long_data %>%
  group_by(year_month) %>%
  summarise(unique_storm_count = n_distinct(storm_name)) %>%
  filter(unique_storm_count >= 2)

# 查看目标年月结果
print(target_months)

3. (可选)关联原数据获取对应风暴信息

如果需要知道这些年月对应的具体风暴,可以把筛选结果关联回原数据:

result_with_storms <- my_data %>%
  filter(
    year_month_min %in% target_months$year_month | 
    year_month_max %in% target_months$year_month
  )

print(result_with_storms)

结果验证

运行后,target_months会输出所有符合条件的年月:

# A tibble: 10 × 2
   year_month unique_storm_count
   <chr>                   <int>
 1 2007-08                     2
 2 2007-09                     2
 3 2008-08                     2
 4 2008-09                     2
 5 2010-09                     2
 6 2017-08                     2
 7 2017-09                     3
 8 2018-08                     2
 9 2019-08                     2
10 2019-09                     2

可以看到,像2008-11(仅PALOMA_2008)、2018-10(仅MICHAEL_2018)这类单风暴年月被自动排除,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:30:50