HenrikBengtsson / listenv

R package: listenv - Environments Behaving As Lists
https://listenv.futureverse.org
30 stars 2 forks source link

TESTS: Add tests for lapply(), apply() etc comparing listenvs with lists #26

Closed HenrikBengtsson closed 6 years ago

HenrikBengtsson commented 8 years ago

Add tests for lapply(), apply() etc. asserting that list environments as input works the same as when lists are used for input. Test with and without dimensions and with and without names/dimnames.

HenrikBengtsson commented 6 years ago

lapply() works, but apply() requires aperm(), cf. Issue #28;

> x <- matrix(as.list(1:6), nrow = 2)
> rownames(x) <- letters[seq_len(nrow(x))]
> colnames(x) <- LETTERS[seq_len(ncol(x))]
> y <- as.listenv(x)
> z0 <- apply(x, MARGIN = 1L, FUN = function(x) sum(unlist(x)))
> z1 <- apply(y, MARGIN = 1L, FUN = function(x) sum(unlist(x)))
Error in aperm.default(X, c(s.call, s.ans)) : 
  invalid first argument, must be an array

Here's an inefficient version of aperm():

aperm.listenv <- function(a, ...) {
  a <- as.list(a)
  a <- aperm(a, ...)
  as.listenv(a)
}

but it works:

> x <- matrix(as.list(1:6), nrow = 2)
> rownames(x) <- letters[seq_len(nrow(x))]
> colnames(x) <- LETTERS[seq_len(ncol(x))]
> y <- as.listenv(x)
> z0 <- apply(x, MARGIN = 1L, FUN = function(x) sum(unlist(x)))
> z1 <- apply(y, MARGIN = 1L, FUN = function(x) sum(unlist(x)))
> stopifnot(identical(z1, z0))