[Rd] inconsistency between as.list(df) and as.list(mat) with mode(mat) == "list"

Gabriel Becker g@bembecker @end|ng |rom gm@||@com
Mon Jan 31 21:11:10 CET 2022


Hi All,

I ran into the following the other day:

> mat <- matrix(1:6, nrow = 2)

> as.list(mat)

[[1]]

[1] 1


*<snip>*


[[6]]

[1] 6


> mat2 <- mat

> mode(mat2) <- "list"

> as.list(mat2)

     [,1] [,2] [,3]

[1,] 1    3    5

[2,] 2    4    6

>


I realize this is not guaranteed by the documentation, and the behavior is
technically (if I would argue fairly subtly) as documented. Generally,
however, as.list returns something without dimensions (other than length),
regardless of the dimensions of the input.

Furthermore, this behavior agrees with neither the data.frame (which are
lists) method nor the non-list-mode matrix behavior which comes from the
default behavior. Both result in a non-dimensioned object (the data.frame
method explicitly and intentionally so).

Matrices of mode "list" are fairly rare, in practice, I would think, but I
wonder if the as.list behavior for them should agree with that of similar
dimensioned objects (data.frames and non-list-mode matrices). As a user, I
certainly expected it to, and had to read the docs with a careful eye
before I realized what was happening and why.

For the record, as.vector  does not drop dimension (or anything else) from
data.frames nor list-matrices, so there the behaviors agree, although we do
get:

> is.vector(mat)

[1] FALSE

> is.vector(mat2)

[1] FALSE

> is.vector(mtcars)

[1] FALSE


Which does make the fact that for the latter two as.vector returns the
objects unmodified somewhat puzzling.

I wonder if as.list and as.vector could get a strict argument - it could
default to FALSE for a deprecation period, or forever if preferred by
R-core -  where attributes are always stripped for 'strict' conversions.

Also, as a final aside, the documentation at ?as.list says:

 Attributes may be

     dropped unless the argument already is a list or expression.

     (This is inconsistent with functions such as ‘as.character’ which

     always drop attributes, *and is for efficiency since lists can be*

*     expensive to copy.*)


(emphasis mine). Is this still the case with shallow duplication? I was
under the impression that it was not.


Best,

~G

	[[alternative HTML version deleted]]



More information about the R-devel mailing list