Search code examples
rsortingmatrixdatasetcbind

R convert character list to matrices with empty values


in R, I have a character list:

> column_list
> "C", "F", "G", "M", "O", "Y", "Z"
> typeof(column_list)
> "character"

I wish to populate each item in this list with 0s on a defined length N so that it is a matrix that looks like this:

C   F   G   M   O   Y   Z
0   0   0   0   0   0   0
0   0   0   0   0   0   0
... n times

I then want to combine this matrix (using cbind?) to another matrix and order it alphabetically.

A    B    D   E   H    I ...
.1  .2   .1  .5  .1   .1
 0  .2   .3   0   0   .2
.1   0   .1  .1   0   .3
...

such that my new matrix looks like this

 A   B   C    D   E   F    G    H    I ...
.1  .2   0   .1  .5   0    0   .1   .1
 0  .2   0   .3   0   0    0    0   .2
.1   0   0   .1  .1   0    0    0   .3
 ...

How can I do these two steps?


Solution

  • You can use the following steps as guidance to achieve your code or make a function.

    In the fist step use matrix() in conjuction with an additional parameter NROW and the length of the character vector column_list to define the number of rows and columns of your zero-matrix. The function take advantage of the recycling property and populated the matrix elements with zeros.

    The second step is combine, as you say, the zero matrix (X) with another (Y) matrix with cbind to have the Z matrix . The following assumptions must be consider: Y has the same number of rows and the columns of Y has different names (to properly identify the procedence). Then, you just reorder your matrix with square parenthesis and the function order() based on the column names of the new matrix (Z).

    # STEP 1: create the matrix based on a character vector (ncol) and 
    # a NROW parameter (nrow) and populate values with 0
    column_list <- c("C", "F", "G", "M", "O", "Y", "Z")
    NROW <- 10
    X <- matrix(0, nrow = NROW, ncol = length(column_list))
    colnames(X) <- column_list
    
    # STEP 2: Given another matrix Y, assume that have same number of rows and
    # different column names. Bind both matrices by column and order the column
    # based on the name of these (alphabetically)
    Y <- matrix(1, nrow = 10, ncol = 2)   # create another matrix 
    colnames(Y) <- c("D", "L")            # with colnames D and L
    
    Z <- cbind(X, Y)                      # combine
    Z <- Z[, order(colnames(Z))]          # order based on the column names