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

如何在R中按分组统计数据框列的数值出现次数(排除NA)

按分组统计非NA数值的出现次数(data.table实现)

Got it, let's sort this out for you! You're looking to count the total number of non-NA values in the Demand column, grouped by Material—not the number of unique values (which is what your current uniqueN() code does).

The Problem with Your Current Code

Your existing line:

master_data_long_sub[,freq:=uniqueN(Demand),by=.(Material)]

uses uniqueN(), which counts distinct values in each group. For Material 1111, that would return 3 (since the unique non-NA Demand values are 2, 3, 5)—but you need the total count of non-NA entries, which is 4.

The Correct Solution

To count all non-NA values per group, use sum(!is.na(Demand)) inside your data.table grouping. This checks each entry in Demand:

  • is.na(Demand) returns TRUE for NA values, FALSE otherwise
  • !is.na(Demand) flips that to TRUE for non-NA values
  • sum() adds up all the TRUE values (treated as 1) to get the total count

Here's the full code:

Step 1: Example Data (matching your sample)

library(data.table)
master_data_long_sub <- data.table(
  Material = c(1111, 1111, 1111, 1111, 1111, 2222),
  Demand = c(2, 3, 2, NA, 5, 10)
)

Step 2: Calculate Non-NA Counts per Group

master_data_long_sub[, freq := sum(!is.na(Demand)), by = .(Material)]

Result:

Material Demand freq
1:     1111      2    4
2:     1111      3    4
3:     1111      2    4
4:     1111     NA    4
5:     1111      5    4
6:     2222     10    1

As you can see, Material 1111 gets the desired count of 4, and Material 2222 gets 1 (since it has one non-NA Demand value).

Alternative Approach

You can also use .N (data.table's built-in count of rows) combined with a filter, though the first method is more explicit:

master_data_long_sub[, freq := .N[!is.na(Demand)], by = .(Material)]

Either way works—pick whichever makes more sense to you!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:09:19