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

R中如何计算10^n行的列总和并存储到新dataframe

R 实现前N行指定列求和方案

基础R实现(无需额外安装包)

# 定义需要计算的目标行数量(10^1到10^4)
n_list <- 10^(1:4)

# 遍历计算每个行数对应的列总和,拼接为结果表
result <- do.call(rbind, lapply(n_list, function(n){
  # 截取前n行的数值列计算总和,colSums比apply效率更高
  sum_res <- colSums(df[1:n, c("Value1", "Value2")], na.rm = FALSE)
  # 组装为单行数据返回
  data.frame(
    No_of_rows = n,
    Value1 = sum_res["Value1"],
    Value2 = sum_res["Value2"],
    row.names = NULL
  )
}))

Tidyverse 简洁实现

library(tidyverse)

n_list <- 10^(1:4)

result <- map_dfr(n_list, ~{
  df %>%
    # 取前N行
    slice_head(n = .x) %>%
    # 汇总计算两列总和
    summarise(
      No_of_rows = .x,
      Value1 = sum(Value1, na.rm = FALSE),
      Value2 = sum(Value2, na.rm = FALSE)
    )
})

注意事项

  • 求和时不要包含Date列,通过列名指定计算列比用列索引更稳妥,可避免列顺序变动导致的计算错误
  • 若数据存在缺失值,将na.rm参数改为TRUE即可跳过缺失值计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:54:08