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

如何按国家分组计算指定年份IV值差值并生成新数据集

R代码实现指定数据处理需求

代码实现

# 加载dplyr包(若未安装需先执行install.packages("dplyr"))
library(dplyr)

# 原始数据集
df <- structure(list(country = c("Poland", "Poland", "Poland", "Poland", "Poland", "Poland","Portugal", "Portugal", "Portugal", "Portugal", "Portugal", "Portugal", "Spain", "Spain", "Spain", "Spain", "Spain", "Spain"), Code = c("POL", "POL", "POL", "POL", "POL", "POL", "PRT", "PRT", "PRT", "PRT", "PRT", "PRT", "ESP", "ESP", "ESP", "ESP", "ESP", "ESP"), year = c(1950, 1951, 1952, 1953, 1954,1955, 1950, 1951, 1952, 1953, 1954, 1955, 1950, 1951, 1952, 1953, 1954, 1955), IV = c(1, 1, 1, 2, 3, 3, 1, 1, 1, 2, 2, 1, 1, 1, 2, 3, 4, 5)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -18L))

# 数据处理流程
newdata <- df %>%
  # 按国家和代码分组,确保每个国家内部独立计算
  group_by(country, Code) %>%
  # 计算目标年份的IV差值,存入newIV
  mutate(
    newIV = case_when(
      year == 1955 ~ IV - IV[year == 1952],
      year == 1954 ~ IV - IV[year == 1951],
      year == 1953 ~ IV - IV[year == 1950],
      TRUE ~ NA_real_
    )
  ) %>%
  # 仅保留1953、1954、1955年的数据
  filter(year %in% c(1953, 1954, 1955)) %>%
  # 取消分组,恢复普通数据框结构
  ungroup()

# 查看最终结果
print(newdata)

代码说明

  • 依赖dplyr包,若未安装需先运行install.packages("dplyr")完成安装
  • group_by保证每个国家内部的差值计算独立进行,不会跨国家混淆数据
  • case_when针对每个目标年份匹配对应的基准年份,计算IV值的差值
  • filter直接筛选出需要保留的年份,自动剔除1950-1952年的数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:42:38