Search code examples
rmatrix

Fill R matrix based on the list with row IDs


I have a matrix in R with ids as rownames and colnames. I also have a list of ids. For rownames which are not in id list I need to fill row with NA.

id_list <- c(1079, 1081, 1082, 1083)

mat <- matrix(1, nrow = 5, ncol = 5)

rownames(mat) <- colnames(mat) <- c(1079, 1080, 1081, 1082, 1083)

Desired result:

1079 1080 1081 1082 1083
1079 1 1 1 1 1
1080 NA NA NA NA NA
1081 1 1 1 1 1
1082 1 1 1 1 1
1083 1 1 1 1 1

Solution

  • Determine the rows in the matrix whose names are not included in id_list by using the expression !rownames(mat) %in% id_list. This creates a logical vector where TRUE indicates row names that are absent from id_list. Next, use this vector to index those specific rows in the matrix and assign NA to all their elements.

    mat[!rownames(mat) %in% id_list, ] <- NA
    mat
    
         1079 1080 1081 1082 1083
    1079    1    1    1    1    1
    1080   NA   NA   NA   NA   NA
    1081    1    1    1    1    1
    1082    1    1    1    1    1
    1083    1    1    1    1    1