Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Different data structures for storing a collection of data values in RAM. The
most common data structures in R are: Vectors, Factors, Matrices, Data Frames,
Lists, Arrays.
They also differ according to homogeneity of elements they can contain: while
all elements contained in vector, matrix and array must be of the same type, list
and data frame can contain multiple types.
Vectors
A collection of values that all have the same data type. The elements of a vector
are all numbers, giving a numeric vector, or all character values, giving a
character vector.
A vector is a one-dimensional data structure and all of its elements are of the
same data type.
> numbers[1]
[1] 10
> numbers[1:4]
[1] 10 20 30 40
[1] 20 40
Factors
A collection of values that all come from a fixed set of possible values. A factor
is similar to a vector, except that the values within a factor are limited to a fixed
set of possible values.
Matrices
A two-dimensional collection of values that all have the same type. The values
are arranged in rows and columns.
A matrix is a two-dimensional data structure and all of its elements are of the
same type.
> foo
[,1] [,2]
[1,] 1 3
[2,] 2 4
> foo
[,1] [,2]
[1,] 1 2
[2,] 3 4
mat[1,2]# returns the element in the first row of the second column.
Arrays
There is also an array data structure that extends this idea to more than two
dimensions.
a <-matrix(c(1,1,1,1) , 2, 2)
b <-matrix(c(2,2,2,2) , 2, 2)
Data frames
A collection of vectors that all have the same length. This is like a matrix,
except that each column can contain a different data type.
sex <-c(M, M, F)
age <-c(27,26,26)
foo <-data.frame(name,sex,age)
foo$age[2]# returns the second element of the age vector in the data frame
foo[1, ]
foo[, 1]
Lists
Lists may include vectors, arrays, matrices, data frames and other lists.
This is a very flexible data structure. Lists can be used to store any combination
of data values together.
A list is a hierarchical data structure and each component of a list may be any
type of data structure whatsoever.
vec <-c(1,2,3,4)
mat <-matrix(vec,2,2)
> foo[[1]]
[1] 1 2 3 4
> foo[[2]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
> foo[[2]][1,]
[1] 1 3