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

R语言实现同一产品不同年份售价对比的代码求解

解决方案

基础R实现步骤

先将两年的销售数据转为R的数据框,合并后生成指定格式的对比字符串:

# 定义2009年销售数据
df_2009 <- data.frame(
  People = c("A", "B", "C"),
  car = c(1000, 2000, 6977),
  house = c(10000, 7987, 4746),
  watch = c(30, 68, 99),
  dress = c(5, 9, 56),
  jewel = c(50, 78, 367),
  stringsAsFactors = FALSE
)

# 定义2020年销售数据
df_2020 <- data.frame(
  People = c("A", "B", "C"),
  car = c(8700, 8900, 2577),
  house = c(10800, 9987, 40046),
  watch = c(39, 46, 100),
  dress = c(7, 56, 50),
  jewel = c(44, 134, 399),
  stringsAsFactors = FALSE
)

# 按销售人员合并两年数据,添加年份后缀区分列
merged_df <- merge(df_2020, df_2009, by = "People", suffixes = c("_2020", "_2009"))

# 初始化结果数据框
result_df <- data.frame(People = merged_df$People, stringsAsFactors = FALSE)

# 遍历产品列,生成"2020/2009"格式的对比字符串
products <- c("car", "house", "watch", "dress", "jewel")
for (prod in products) {
  result_df[[prod]] <- paste(merged_df[[paste0(prod, "_2020")]], 
                             merged_df[[paste0(prod, "_2009")]], 
                             sep = "/")
}

# 输出结果(隐藏行号)
print(result_df, row.names = FALSE)

执行后会输出你需要的格式:

People       car        house watch dress jewel
     A 8700/1000 10800/10000  39/30   7/5  44/50
     B 8900/2000   9987/7987  46/68  56/9 134/78
     C 2577/6977 40046/4746 100/99  50/56 399/367

Tidyverse(dplyr)实现

如果习惯用tidyverse工具集,代码会更简洁:

library(dplyr)

result_df <- df_2020 %>%
  inner_join(df_2009, by = "People") %>%
  mutate(
    car = paste(car.x, car.y, sep = "/"),
    house = paste(house.x, house.y, sep = "/"),
    watch = paste(watch.x, watch.y, sep = "/"),
    dress = paste(dress.x, dress.y, sep = "/"),
    jewel = paste(jewel.x, jewel.y, sep = "/")
  ) %>%
  select(People, car, house, watch, dress, jewel)

print(result_df, row.names = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:42:09