Data structures in R: Is "table" a special data structure or is it just an array?

In http://adv-r.had.co.nz/Data-structures.html the following data structures are mentioned: lists, vectors, matrices, arrays, data frames.
How is the "table" data structure classified in R? Is it just an array or even just a vector?

Using the built in Titanic table, we get this info:

> class(Titanic)
[1] "table"
> mode(Titanic)
[1] "numeric"

In the help for table, it says "....an object of class "table", an array of integer values" implying that a table object is just an array.

I just wanted to check this. I was going to ask the same question on StackOverflow, but this forum seems more friendly.

I guess it depends on what you mean by "just an array". It is basically an array but, having been given the class "table", it is handled differently by functions which have a method dedicated to tables, like plot(). The table and the matrix in the example below contain the same values and have the same dimension names but result in different plots.

set.seed(35412)
df <- data.frame(X = sample(LETTERS[1:4], 20, replace = TRUE),
                 Y = sample(LETTERS[25:26], 20, replace = TRUE))

Tbl <- table(df$X, df$Y)
Tbl
#>    
#>     Y Z
#>   A 2 4
#>   B 4 5
#>   C 1 1
#>   D 1 2

str(Tbl)
#>  'table' int [1:4, 1:2] 2 4 1 1 4 5 1 2
#>  - attr(*, "dimnames")=List of 2
#>   ..$ : chr [1:4] "A" "B" "C" "D"
#>   ..$ : chr [1:2] "Y" "Z"
plot(Tbl)

MAT <- matrix(c(2,4,1,1,4,5,1,2), nrow = 4)

dimnames(MAT) <- list(c("A", "B", "C", "D"), c("Y", "Z"))
MAT
#>   Y Z
#> A 2 4
#> B 4 5
#> C 1 1
#> D 1 2
str(MAT)
#>  num [1:4, 1:2] 2 4 1 1 4 5 1 2
#>  - attr(*, "dimnames")=List of 2
#>   ..$ : chr [1:4] "A" "B" "C" "D"
#>   ..$ : chr [1:2] "Y" "Z"
plot(MAT)

Created on 2019-03-12 by the reprex package (v0.2.1)

2 Likes

By the way, as I understand it, the difference between a matrix or array and a vector is just in the attributes. By wiping out the attributes of MAT from my previous post, I get a vector.

attributes(MAT) <- NULL
MAT
[1] 2 4 1 1 4 5 1 2
1 Like

Thank you. You answered my question.
Ultimately, I was wondering about what are the fundamental data structures in R. In Python, for example, we have elementary data types, lists, dictionaries, tuples, and a few others. In Wickham's book, he distinguishes between 5 structures (vectors, matrices, arrays, lists, data frames), yet he did not mention tables here, and I was wondering how the fitted in to the data structure types of R.

If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).

Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.

Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.