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

R语言按列计算每局游戏各玩家IX指标并求和的实现问题

你可以通过以下两种常用方式实现需求,运行后输出结果和你给出的预期完全一致:

方式1:tidyverse(dplyr)实现,可读性更高

# 加载依赖包
library(dplyr)

df <- df %>%
  # 按行计算
  rowwise() %>%
  mutate(
    # 定义系数映射函数,根据公式类型和得分返回对应乘数
    get_multi = function(formula_type, score) {
      # 得分0或3直接返回0,不计入计算
      if (score %in% c(0, 3)) return(0)
      if (formula_type == "PosdownNegUp") {
        case_when(
          score == 1 ~ 1,
          score == 2 ~ 0.5,
          score == 4 ~ -0.5,
          score == 5 ~ -1
        )
      } else if (formula_type == "NegdownPosUp") {
        case_when(
          score == 1 ~ -1,
          score == 2 ~ -0.5,
          score == 4 ~ 0.5,
          score == 5 ~ 1
        )
      }
    },
    # 分别计算三个玩家的单玩家IX值
    ix1 = weight001 * get_multi(FORMULA, r001),
    ix2 = weight002 * get_multi(FORMULA, r002),
    ix3 = weight003 * get_multi(FORMULA, r003),
    # 求和得到最终IXsum
    IXsum = ix1 + ix2 + ix3
  ) %>%
  ungroup() %>%
  # 可选操作:删除中间计算的临时列
  select(-ix1, -ix2, -ix3)

方式2:base R实现,无需额外安装依赖

# 定义单行计算函数
calc_ixsum <- function(row) {
  formula_t <- row[["FORMULA"]]
  # 提取当前行三个玩家的得分和对应权重
  rs <- as.numeric(c(row[["r001"]], row[["r002"]], row[["r003"]]))
  ws <- as.numeric(c(row[["weight001"]], row[["weight002"]], row[["weight003"]]))
  total <- 0
  for (i in 1:3) {
    s <- rs[i]
    w <- ws[i]
    # 跳过0、3分的玩家
    if (s %in% c(0,3)) next
    # 匹配对应乘数
    if (formula_t == "PosdownNegUp") {
      multi <- switch(as.character(s),
               "1" = 1,
               "2" = 0.5,
               "4" = -0.5,
               "5" = -1,
               0)
    } else {
      multi <- switch(as.character(s),
               "1" = -1,
               "2" = -0.5,
               "4" = 0.5,
               "5" = 1,
               0)
    }
    total <- total + w * multi
  }
  return(total)
}

# 遍历每行计算IXsum
df$IXsum <- apply(df, 1, calc_ixsum)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:24:04