Well, the precise reason as to "why" is that this is the source code for as.data.frame.table
(just enter that name in an R console with no other punctuation to see this in the console):
function(x, row.names = NULL, ..., responseName = "Freq",
stringsAsFactors = TRUE, sep = "", base = list(LETTERS)) {
ex <- quote(
data.frame(
do.call(
"expand.grid",
c(
dimnames(provideDimnames(x, sep = sep, base = base)),
KEEP.OUT.ATTRS = FALSE,
stringsAsFactors = stringsAsFactors)
),
Freq = c(x), row.names = row.names)
)
names(ex)[3L] <- responseName
eval(ex)
}
Ultimately, what you have with:
tbl <- structure(
c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L),
.Dim = c(4L, 2L),
.Dimnames = structure(
list(
c("1", "2", "3", "4"),
colNames = c("2013 3", "2014 12")
),
.Names = c("", "colNames")
),
class = "table"
)
is an integer
vector with some attributes. When you type tbl
and hit <ENTER>
in an R console it's calling print.table()
(enter print.table
with no other punctuation in an R console to see its source) it goes through some hoops to print what you see as a "rectangular" data structure.
To get your desired result, just do what the print function ultimately does (in a not-as-straightforward-way):
as.data.frame.matrix(tbl)
or using tidyverse idioms:
as.data.frame(tbl) %>%
tidyr::spread(colNames, Freq)
## Var1 2013 3 2014 12
## 1 1 1 1
## 2 2 0 0
## 3 3 0 0
## 4 4 0 0