Skip to content

.stat_over_list() fails for arrays with more than two elements #74

@andreassoteriadesmoj

Description

@andreassoteriadesmoj

Function .stat_over_list() uses apply(), which doesn't work as intended when the array has more than two elements:

alist <- list(
  matrix(1:20, 4),
  matrix(21:40, 4),
  matrix(41:60, 4)
)

# This returns an array, not the average
apply(
    simplify2array(alist),
    seq_along(alist),
    stat
)

# , , 1
# 
# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    5    9   13   17
# [2,]    2    6   10   14   18
# [3,]    3    7   11   15   19
# [4,]    4    8   12   16   20
# 
# , , 2
# 
# [,1] [,2] [,3] [,4] [,5]
# [1,]   21   25   29   33   37
# [2,]   22   26   30   34   38
# [3,]   23   27   31   35   39
# [4,]   24   28   32   36   40
# 
# , , 3
# 
# [,1] [,2] [,3] [,4] [,5]
# [1,]   41   45   49   53   57
# [2,]   42   46   50   54   58
# [3,]   43   47   51   55   59
# [4,]   44   48   52   56   60

I misunderstood the way apply() works with arrays as opposed to dataframes/lists. The loop index shouldn't be one-dimensional (i.e. seq_along(alist)), but two-dimensional- specifically, it should be 1:2:

mean_array <- apply(
  simplify2array(alist),
  1:2,
  stat
)

mean_list <- Reduce(`+`, alist) / length(alist)

# TRUE
identical(
  mean_array,
  mean_list
)

I'll fix this as part of this PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions