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

如何在R中结合across、summarize和n()计算列非NA值数量?

问题分析与修正方案

问题根源

你的代码存在两个关键问题:

  1. 统计非NA行数的函数错误:n(.x)返回的是列的总行数(不会过滤NA),而非你需要的非NA值数量,无法得到n_q2=1、n_q3=2这类正确结果。
  2. 列结构嵌套:直接在summarise中把across的结果赋值给n和avg,会生成两个列表类型的嵌套列,无法展开成预期的扁平化列结构。

修正代码

使用across的.names参数自定义输出列名,同时替换正确的统计函数,就能直接得到目标结果:

library(dplyr)

test <- tibble(student = c("j", "c", "s"),
               q1 = c(1, 2, 3),
               q2 = c(NA_real_, NA_real_, 4),
               q3 = c(43, NA_real_, 232))

test %>%
  summarise(
    # 统计非NA值行数,生成n_q1/n_q2/n_q3列
    across(starts_with("q"), ~sum(!is.na(.x)), .names = "n_{col}"),
    # 计算均值并保留两位小数,生成avg_q1/avg_q2/avg_q3列
    across(starts_with("q"), ~round(mean(.x, na.rm = TRUE), 2), .names = "avg_{col}")
  )

输出结果

运行后会得到与expected_outcome完全一致的扁平化表格:

# A tibble: 1 × 6
  n_q1 n_q2 n_q3 avg_q1 avg_q2 avg_q3
  <int> <int> <int>  <dbl>  <dbl>  <dbl>
1     3     1     2      2      4    138

内容的提问来源于stack exchange,提问作者J.Sabree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:10:46