I have found something odd today, I wanted to ask you if there was a logical reason for what I am seeing, or if you think this is a bug that should be reported to the R-devel team:
df <- data.frame(a = 1L:10L)
class(df$a)
# [1] "integer"
m <- as.matrix(df)
class(m[, "a"])
# [1] "integer"
No surprise so far: as.matrix preserves the data mode, here “integer”. However, with an empty (no rows) data.frame:
df <- data.frame(a = integer(0))
class(df$a)
# [1] "integer"
m <- as.matrix(df)
class(m[, "a"])
# [1] "logical"
Any idea why the mode changes from “integer” to “logical” here? I am using version 2.13.1
Thank you.
This is because of this one line in
as.matrix.data.frame:Basically, if any dimensions are zero, you get an array “full” of
NA. I say “full” because there aren’t really any observations because one of the dimensions is zero.The reason the class is
logicalis because that’s the class ofNA. There are specialNAfor other classes, but they’re not really necessary here. For example: