Multi-dimensional objects in R
A vector is a one-dimensional object in R. Usually the vector looks like a row but it really acts like a column. When you make more complicated objects you add more dimensions, commonly used multi-dimensional objects are:
- matrix
- frame
- table
- array
- list
A matrix is a 2-dimensional object with rows and columns. A data.frame is also 2-dimensional with rows and columns. A table can have more than 2 dimensions – a three-dimensional table would appear as several two-dimensional tables. An array is similar to a table (the difference is largely how you build it to start with). A list is the most “primitive” of the objects and is a loose collection of other objects, bundled together.
A matrix contains rows and columns but all the data in the matrix must be of the same type, that is, all numbers or all text. You can think of a matrix as a single vector that happens to be split up into rows and columns. In fact, one way to make a matrix is to do just that:
> matrix(1:12, ncol = 4)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
A data.frame also contains rows and columns but the columns can be of different types, so you can have one column that is numeric, one that is character and one that is a factor.
a <- 1:4 b <- c("one", "two", "three", "four") c <- gl(2, 2, labels = c("high", "low")) > data.frame(b, a, c) b a c 1 one 1 high 2 two 2 high 3 three 3 low 4 four 4 low
You can use the class() command to tell you what kind of object you are dealing with.
Comments are closed.