Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dimensions for list environments? #11

Closed
HenrikBengtsson opened this issue Oct 8, 2015 · 3 comments
Closed

Support dimensions for list environments? #11

HenrikBengtsson opened this issue Oct 8, 2015 · 3 comments

Comments

@HenrikBengtsson
Copy link
Collaborator

With lists one can do:

> x <- as.list(1:6)
> dim(x) <- c(2,3)
> x
     [,1] [,2] [,3]
[1,] 1    3    5
[2,] 2    4    6
> str(x)
List of 6
 $ : int 1
 $ : int 2
 $ : int 3
 $ : int 4
 $ : int 5
 $ : int 6
 - attr(*, "dim")= int [1:2] 2 3

> x[1,3]
[[1]]
[1] 5

> x[[1,3]]
[1] 5

> x[1,]
[[1]]
[1] 1

[[2]]
[1] 3

[[3]]
[1] 5

> x[,2]
[[1]]
[1] 3

[[2]]
[1] 4

Can we add something similar to list environments?

@HenrikBengtsson
Copy link
Collaborator Author

Because list environments formally are environments in R, the internal code prevents us from setting attributes dim and dimnames, e.g.

> x <- as.listenv(as.list(1:6))
> x
`listenv` with 6 elements that are not named.
> dim(x) <- c(2,3)
Error in dim(x) <- c(2, 3) : invalid first argument
> attr(x, "dim") <- c(2,3)
Error in attr(x, "dim") <- c(2, 3) : invalid first argument
> attributes(x) <- list(dim=c(2,3))
Error in attributes(x) <- list(dim = c(2, 3)) : invalid first argument

So there's some built-in/low-level protection from setting attributes with those names on environments. However, we can set others, e.g.

> attr(x, ".dim") <- c(2,3)
> attr(x, ".dim")
[1] 2 3

Also, it turns out we at least can override dim() and dim()<- for list environments, e.g.

> dim.listenv <- function(x) attr(x, ".dim")
> `dim<-.listenv` <- function(x, value) { attr(x, ".dim") <- as.integer(value); x }
> dim(x) <- c(3,2)
> dim(x)
[1] 3 2

Similarly for dimnames() and dimnames()<-, e.g.

> dimnames.listenv <- function(x) attr(x, ".dimnames")
> `dimnames<-.listenv` <- function(x, value) { attr(x, ".dimnames") <- as.list(value); x }

> dimnames(x) <- list(c("R1", "R2"), c("C1", "C2", "C3"))
> dimnames(x)
[[1]]
[1] "R1" "R2"

[[2]]
[1] "C1" "C2" "C3"

Maybe this is enough? Though, not sure that dimensions and their names should be stored as attributes per se or internal objects of the list environment, cf. names(x) and map(x).

@HenrikBengtsson
Copy link
Collaborator Author

Added some basic support for subsetting single elements with multiple dimensions (e.g. x[[2,"b"]]), cf. commits 8cce576 and 1194aa7.

@HenrikBengtsson
Copy link
Collaborator Author

All of the above is now in the develop branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant