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

在R中基于另一数据框,用函数为数据框添加计算列

数据处理需求与实现

原始数据

df1

df1 <- data.frame(
  Name = c("Ben", "Ben", "Lucy", "Lucy", "Lucy"),
  t = c(1.1, 2.3, 1.2, 2.5, 2.7)
)

df2

df2 <- data.frame(
  Name = c("Ben", "Ben", "Ben", "Lucy", "Lucy", "Lucy"),
  t = c(1, 2, 3, 1, 2, 3),
  c1 = c(0, 1, 1, 1, 0, 0),
  c2 = c(0, 0, 0, 1, 0, 0),
  c3 = c(0, 0, 1, 0, 1, 2)
)

需求说明

为df1添加一列,计算规则如下:

  • 对每行的t值计算向上取整(ceiling)
  • 根据Name和取整后的t值,匹配df2中对应行,计算exp(c1*b1 + c2*b2 + c3*b3)(其中b1=b2=b3=1)
  • 将同一Name下的所有计算结果求和,作为该人员每行的新增列值

示例:

  • Ben的两行:取整后t分别为2、3,对应df2的exp值为exp(1)、exp(2),求和结果为exp(1)+exp(2)
  • Lucy的三行:取整后t分别为2、3、3,对应df2的exp值为exp(1)、exp(2)、exp(2),求和结果为exp(1)+2*exp(2)

R代码实现

library(dplyr)

# 定义参数
b1 <- 1
b2 <- 1
b3 <- 1

# 预处理df2,计算每个(Name, t)对应的exp值
df2_processed <- df2 %>%
  mutate(exp_val = exp(c1*b1 + c2*b2 + c3*b3))

# 处理df1,完成匹配与求和
df1_result <- df1 %>%
  mutate(t_ceiling = ceiling(t)) %>%
  left_join(df2_processed, by = c("Name", "t_ceiling" = "t")) %>%
  group_by(Name) %>%
  mutate(total_exp = sum(exp_val, na.rm = TRUE)) %>%
  ungroup() %>%
  select(Name, t, total_exp)

# 查看结果
print(df1_result)

输出结果

Name   t total_exp
1   Ben 1.1  10.10733
2   Ben 2.3  10.10733
3  Lucy 1.2  17.49603
4  Lucy 2.5  17.49603
5  Lucy 2.7  17.49603

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:22:15