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

R语言计算两个数据框df1相对df2所有数值的百分比

实现代码(基于tidyverse)

# 加载依赖包
library(dplyr)
library(tidyr)

# 构造示例数据
df1 = data.frame('gen' = c('a', 'b', 'c', 'd'), 'mm' = c(10, 20, 30, 40), 'nn' = c(50,60,70,80))
df2 = data.frame('gen' = c('x', 'y'), 'mm' = c(10,20), 'nn' = c(20,30))

# 处理df2为宽格式基准值
df2_wide <- df2 %>%
  pivot_longer(-gen, names_to = "col", values_to = "val") %>%
  mutate(col_id = recode(col, mm = 1, nn = 2),
         col_name = paste0(gen, ".", col_id)) %>%
  select(col_name, val) %>%
  pivot_wider(names_from = col_name, values_from = val)

# 按公式计算结果
res <- df1 %>%
  crossing(df2_wide) %>%
  mutate(
    x.1 = (mm - x.1)/x.1 * 100,
    y.1 = (mm - y.1)/y.1 * 100,
    x.2 = (nn - x.2)/x.2 * 100,
    y.2 = (nn - y.2)/y.2 * 100
  ) %>%
  select(gen, x.1, y.1, x.2, y.2) %>%
  mutate(across(where(is.numeric), ~round(.x, 2)))

输出结果

gen x.1 y.1 x.2   y.2
1   a   0 -50 150  66.67
2   b 100   0 200 100.00
3   c 200  50 250 133.33
4   d 300 100 300 166.67

注:你给出的预期结果中d行y.2列的167.67为笔误,按公式计算的正确值为166.67。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:06:06