1
votes

I am trying to populate a matrix with values from a vector, where the name of each value is a combination of the matrix' col- and row names.

set.seed(1001)
mat <- matrix(nrow = 2, ncol = 3, dimnames = list(c("one", "two"), c("house", "tree", "flower")))
vec <- sample.int(10, 5)
names(vec) <- c("one_house", "one_flower", "two_tree", "two_house", "one_tree")

The output I'm looking for is this:

matrix(c(4, 7, 6, 2, 3, NA), nrow = 2, ncol = 3, dimnames = list(c("one", "two"), c("house", "tree", "flower")))

Any help with this would be greatly appreciated.

1
I get a different value from seed you showedakrun

1 Answers

1
votes

We can split the names of the vector by _ and do an assignment based on row/column name attributes in the mat

mat[do.call(rbind, strsplit(names(vec), "_"))] <- vec

-output

mat
#    house tree flower
#one     7    9      3
#two     8   10     NA

Or, if we don't have a dataset to replace, we can construct a data.frame and use xtabs to reshape the data

xtabs(vec ~ V1 + V2, as.data.frame(do.call(rbind, strsplit(names(vec), "_"))))