Saturday 15 September 2012

R adding extra rows in a matrix where row names are unique -



R adding extra rows in a matrix where row names are unique -

i have matrix row names , e , column names b c d e.

b c d e 1 0 0 1 0 e 1 0 0 1 0

i trying create square matrix new rows (3 in case) this.

b c d e 1 0 0 1 0 e 1 0 0 1 0 b 0 0 0 0 0 c 0 0 0 0 0 d 0 0 0 0 0

three new rows names b c & d (unique row names) , pad them zeros.

any advise much appreciated.

use setdiff figure out rows need added, create empty matrix, , rbind them together:

toadd <- setdiff(colnames(mat), rownames(mat)) m <- matrix(0, ncol = ncol(mat), nrow = length(toadd), dimnames = list(toadd, colnames(mat))) rbind(mat, m) # b c d e # 1 0 0 1 0 # e 1 0 0 1 0 # b 0 0 0 0 0 # c 0 0 0 0 0 # d 0 0 0 0 0

this assumes "mat" defined as:

mat <- structure(c(1l, 1l, 0l, 0l, 0l, 0l, 1l, 1l, 0l, 0l), .dim = c(2l, 5l), .dimnames = list(c("a", "e"), c("a", "b", "c", "d", "e")))

r matrix

No comments:

Post a Comment