when column variables do not match row variables in a matrix, add the missing variable as a row of zeros in r

main.r
# Create a sample matrix
mat <- matrix(1:9, nrow = 3)
rownames(mat) <- c("A", "B", "D")

# Get all possible row and column names
all_vars <- union(rownames(mat), colnames(mat))

# Add rows of zeros for missing variables
mat <- rbind(mat, matrix(0, nrow = length(setdiff(all_vars, rownames(mat))), ncol = ncol(mat)))
rownames(mat) <- all_vars

print(mat)
354 chars
13 lines

related categories

gistlibby LogSnag