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

R语言如何对dataframe单条记录内的多个数值进行求和计算

R实现拆分双位数字各位求和的方法

首先先构造你的示例数据:

df <- data.frame(
  teamid = c(1, 2),
  scores = c(10, 11)
)

方法1:数学运算实现(最高效,仅适用于固定两位数的场景)

直接拆分十位和个位相加即可,不需要做类型转换:

df$Combinedscore <- (df$scores %/% 10) + (df$scores %% 10)
# 提取目标列得到最终结果
result <- df[, c("teamid", "Combinedscore")]

方法2:基础R通用实现(适用于任意位数的数字)

核心思路是把数值转成字符串拆分每一位,再转数字求和:

df$Combinedscore <- sapply(as.character(df$scores), function(x) {
  sum(as.numeric(strsplit(x, "")[[1]]))
})
result <- df[, c("teamid", "Combinedscore")]

方法3:tidyverse管道实现

library(dplyr)
library(stringr)

result <- df %>%
  rowwise() %>%
  mutate(Combinedscore = sum(as.numeric(str_split(scores, "")[[1]]))) %>%
  ungroup() %>%
  select(teamid, Combinedscore)

以上三种方法输出的结果均和预期一致:

teamidCombinedscore
11
22

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:36:00