Previous: Arrays Up: Arrays Next: Lists

Ways to create arrays

  1. Common ways to create vectors (or one-dimensional arrays) include:
    > a <- c(3, 7, 9, 11)    # Concatenates numeric values into a vector
    > a <- c("a", "b", "c")  # Concatenates character strings into a vector
    > a <- 1:5               # Creates a vector of integers from 1 to 5 inclusive  
    > a <- rep(1, times = 5) # Creates a vector of 5 repeated `1's
    
    To manipulate a vector:
    > a[10]                # Extracts the 10th value from the vector `a'
    > a[5] <- 3.14         # Inserts 3.14 as the 5th value in the vector `a'
    > a[5:7] <- c(2, 4, 7) # Replaces the 5th through 7th values with 2, 4, and 7
    
    Unlike larger arrays, vectors can be extended without first creating another vector of the correct length. Hence,
    > a <- c(4, 6, 8) 
    > a[5] <- 9       # Inserts a 9 in the 5th position of the vector,
                      #  automatically inserting an `NA' values position 4
    

  2. A factor vector is a special type of vector that allows users to create 45#45 indicator variables in one vector, rather than using 45#45 dummy variables (as in Stata or SPSS). R creates this special class of vector from a pre-existing vector x using the factor() command, which separates x into levels based on the discrete values observed in x. These values may be either integer value or character strings. For example,
    > x <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 9, 9, 9, 9)
    > factor(x)
       [1] 1 1 1 1 1 2 2 2 2 9 9 9 9
       Levels: 1 2 9
    
    By default, factor() creates unordered factors, which are treated as discrete, rather than ordered, levels. Add the optional argument ordered = TRUE to order the factors in the vector:
      
    > x <- c("like", "dislike", "hate", "like", "don't know", "like", "dislike")
    > factor(x, levels = c("hate", "dislike", "like", "don't know"),
    +        ordered = TRUE)
      [1] like    dislike    hate    like   don't know   like   dislike   
    Levels: hate < dislike < like < don't know
    
    The factor() command orders the levels according to the order in the optional argument levels. If you omit the levels command, R will order the values as they occur in the vector. Thus, omitting the levels argument sorts the levels as like < dislike < hate < don't know in the example above. If you omit one or more of the levels in the list of levels, R returns levels values of NA for the missing level(s):
    > factor(x, levels = c("hate", "dislike", "like"), ordered = TRUE)
      [1] like    dislike hate    like    <NA>    like    dislike
    Levels: hate < dislike < like
    
    Use factored vectors within data frames for plotting (see Section [*]), to set the values of the explanatory variables using setx (see Section [*]) and in the ordinal logit and multinomial logit models (see Section [*]).

  3. Build matrices (or two-dimensional arrays) from vectors (one-dimensional arrays). You can create a matrix in two ways:
    1. From a vector: Use the command matrix(vector, nrow = 3#3 , ncol = 2#2 ) to create a 46#46 matrix from the vector by filling in the columns from left to right. For example,
      > matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)
              [,1] [,2] [,3]       # Note that when assigning a vector to a
         [1,]    1    3    5       #  matrix, none of the rows or columns 
         [2,]    2    4    6       #  have names.
      
    2. From two or more vectors of length 3#3 : Use cbind() to combine 2#2 vectors vertically to form a 46#46 matrix, or rbind() to combine 2#2 vectors horizontally to form a 7#7 matrix. For example:
      > x <- c(11, 12, 13)         # Creates a vector `x' of 3 values.
      > y <- c(55, 33, 12)         # Creates another vector `y' of 3 values.  
      > rbind(x, y)                # Creates a 2 x 3 matrix.  Note that row
           [,1] [,2] [,3]          #  1 is named x and row 2 is named y, 
         x   11   12   13          #  according to the order in which the
         y   55   33   12          #  arguments were passed to rbind().
      > cbind(x, y)                # Creates a 3 x 2 matrix.  Note that the
               x  y                #  columns are named according to the
         [1,] 11 55                #  order in which they were passed to
         [2,] 12 33                #  cbind().  
         [3,] 13 12
      
    R supports a variety of matrix functions, including: det(), which returns the matrix's determinant; t(), which transposes the matrix; solve(), which inverts the the matrix; and %*%, which multiplies two matricies. In addition, the dim() command returns the dimensions of your matrix. As with vectors, square brackets extract specific values from a matrix and the assignment mechanism <- replaces values. For example:
    > loo[,3]     		  # Extracts the third column of loo.  
    > loo[1,]      		  # Extracts the first row of loo.  
    > loo[1,3] <- 13          # Inserts 13 as the value for row 1, column 3.  
    > loo[1,] <- c(2,2,3)     # Replaces the first row of loo.
    
    If you encounter problems replacing rows or columns, make sure that the dims() of the vector matches the dims() of the matrix you are trying to replace.

  4. An n-dimensional array is a set of stacked matrices of identical dimensions. For example, you may create a three dimensional array with dimensions 47#47 by stacking 48#48 matrices each with 30#30 rows and 31#31 columns.
    > a <- matrix(8, 2, 3)       # Creates a 2 x 3 matrix populated with 8's.
    > b <- matrix(9, 2, 3)       # Creates a 2 x 3 matrix populated with 9's.
    > array(c(a, b), c(2, 3, 2)) # Creates a 2 x 3 x 2 array with the first
       , , 1                     #  level [,,1] populated with matrix a (8's),
                                 #  and the second level [,,2] populated 
            [,1] [,2] [,3]       #  with matrix b (9's).  
       [1,]    8    8    8       
       [2,]    8    8    8       # Use square brackets to extract values.  For
                                 #  example, [1, 2, 2] extracts the second
       , , 2                     #  value in the first row of the second level.
                                 # You may also use the <- operator to 
            [,1] [,2] [,3]       #  replace values.  
       [1,]    9    9    9
       [2,]    9    9    9
    
    If an array is a one-dimensional vector or two-dimensional matrix, R will treat the array using the more specific method.

Three functions especially helpful for arrays:



Gary King 2011-11-29