lynnyi lynnyi - 20 days ago 5
R Question

Construct matrix with columns of data and zeros, without using for-loop

I have a matrix of numerical data with pesky zero columns I want to remove to do some data processing. I keep track of what columns are zero columns with

is_zero_column <- colSums(matrix) == 0
and remove the zero columns via
matrix <- matrix[,colSums(matrix)!=0]


Now how would I do the reverse, where I use my
is_zero_column
of TRUE/FALSE (TRUE if zero column) to reinsert the zero columns back into my matrix?

If this were not R, I would go for a forloop where I construct a new matrix: (in python-ish pseudocode)

new_matrix;
for i in is_zero_column:
if i is TRUE:
new_matrix <- new_matrix.append_column(rep(0, columnlength))
else:
new_matrix <- new_matrix.append_column(matrix[,1])
matrix <- matrix[,-1]
return new_matrix;


But, this is R, so trying to find a non for loop way of doing this.

Answer

Say if Q is the matrix without zero columns:

Q
#     [,1] [,2]
#[1,]    1    0
#[2,]    0    0
#[3,]    0    1

And is_zero_column is as follows:

is_zero_column = c(F,T,F)

You can create a zero matrix with number of rows equal to number of rows in Q, and number of columns equal to length of is_zero_column vector and then update non zero columns values with values in Q:

Q1 = matrix(0, nrow(Q), length(is_zero_column))
Q1[, !is_zero_column] = Q
Q1
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    0    0
#[3,]    0    0    1
Comments