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

如何为R语言DataFrame按年份添加各品类的c值列?

解决方案

方法一:直接分组赋值(简洁高效)

加载dplyr包后,按年份分组提取对应分类的c值,直接新增列:

library(dplyr)

df_result <- df0 %>%
  group_by(year) %>%
  mutate(
    c1 = unique(c[category == 1]),
    c2 = unique(c[category == 2]),
    c3 = unique(c[category == 3])
  ) %>%
  ungroup()

方法二:构建映射表再连接(扩展性更强)

如果后续分类数量可能变动,这种方法更灵活:

library(dplyr)
library(tidyr)

# 生成年份与各分类c值的映射表
c_mapping <- df0 %>%
  distinct(year, category, c) %>%
  pivot_wider(
    id_cols = year,
    names_from = category,
    names_prefix = "c",
    values_from = c
  )

# 映射表与原数据左连接
df_result <- df0 %>%
  left_join(c_mapping, by = "year")

运行任意一种方法后,df_result的结构和数据都会完全匹配你需要的目标格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:22:17