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)
以上三种方法输出的结果均和预期一致:
| teamid | Combinedscore |
|---|---|
| 1 | 1 |
| 2 | 2 |
内容的提问来源于stack exchange,提问作者user15288243
相关产品推荐
相关产品推荐

