1

If I have data that may be modelled as so:

a1 <- c("bob","bill",0.2)
a2 <- c("bob", "bert", 0.1)
a3 <- c("bill", "bert", 0.1)

my.df <- as.data.frame(rbind(a1, a2, a3), stringsAsFactors = FALSE)

colnames(my.df) <- c("name_1", "name_2", "value")
row.names(my.df) <- NULL

my.names <- unique(as.character(c(my.df$name_1, my.df$name_2)))

my.matrix <- matrix(0, nrow = length(my.names), ncol = length(my.names))

row.names(my.matrix) <- my.names

colnames(my.matrix) <- my.names

How may I fill my.matrix using the values from my.df. The first two columns in my.df describe the coordinates of my.matrix to fill?

0

2 Answers 2

4

You can coerce the first two columns of my.df into an index matrix, and index-assign my.matrix with the remaining column of my.df as the RHS:

my.matrix[as.matrix(my.df[c('name_1','name_2')])] <- as.double(my.df$value);
my.matrix;
##      bob bill bert
## bob    0  0.2  0.1
## bill   0  0.0  0.1
## bert   0  0.0  0.0

I also coerced the RHS to a double, since I assumed you want to preserve the type of my.matrix.

Sign up to request clarification or add additional context in comments.

2 Comments

Great thanks! This worked best with the real data and I was able to easily adapt it to fill the other half of the matrix.
I have a follow up question, is it possible when the data is missing to set the cell as empty instead of 0?
2

An easy solution using a for loop:

my.df$value <- as.numeric(my.df$value)
for (i in 1:nrow(my.df)) {
   my.matrix[rownames(my.matrix) == my.df$name_1[i], 
             colnames(my.matrix) == my.df$name_2[i]] <- my.df$value[i]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.