如何在R中按分组统计数据框列的数值出现次数(排除NA)
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)returnsTRUEfor NA values,FALSEotherwise!is.na(Demand)flips that toTRUEfor non-NA valuessum()adds up all theTRUEvalues (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

