Oddly mean calculationwhen applying "mean" by grouping in data.table

Open
#5,354 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

Start by running the reproducible R/data.table example from the issue and compare the grouped mean() and lapply() results. Trace how grouped expressions are evaluated, then verify the behavior against the expected per-row results shown in the report. Done means the inconsistency is resolved or clearly documented with coverage for this example.

Written by the indexing model from the issue text.

Description

GForce

This issue is detailed reported in https://stackoverflow.com/questions/71534176.

The following result behaves oddly, please see results for 'mean_2' in lines 2,4,5,6,7,9:

dt <- data.table(
    a   = 10:20
  , id  = c(1:3, 2,4,2,5)
  , text = letters[1:4]
)
dt[, mean_a  := mean(a, na.rm=T),         by = .(id)]
dt[, mean_a2 := lapply(a, mean, na.rm=T), by = .(id)]
dt[order(id)]

        a    id   text mean_a mean_a2
    <int> <num> <char>  <num>   <num>
 1:    10     1      a   13.5      10
 2:    17     1      d   13.5      10
 3:    11     2      b   15.4      11
 4:    13     2      d   15.4      11
 5:    15     2      b   15.4      11
 6:    18     2      a   15.4      11
 7:    20     2      c   15.4      11
 8:    12     3      c   15.5      12
 9:    19     3      b   15.5      12
10:    14     4      a   14.0      14
11:    16     5      c   16.0      16

Now compare with the expected results provided by:

dt[, mean_a2 := lapply(a, function(x) {
  message("Contents of x: ", x, "")
  foo <- mean(x, na.rm=T)
  foo
}), by = .(id)]

Contents of x: 10
Contents of x: 17
Contents of x: 11
Contents of x: 13
Contents of x: 15
Contents of x: 18
Contents of x: 20
Contents of x: 12
Contents of x: 19
Contents of x: 14
Contents of x: 16

It seems to be inconsistente in the first code.

Dominant language
R
Stars
3.9k
Forks
1.1k
Avg merge
14h 4m
Merged PRs (30d)
4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Rdatatable/data.table

All issues in Rdatatable/data.table

Similar issues

More R issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.