How to place values into a matrix when the row/col information is known?

I have a list of 15 values with row and column information, corresponding to where they should go in a 5x5 matrix. How can I use this information to place them into my 5x5 matrix?

If this were a full set of 25 values, I could use dcast from the reshape2 package. But I only have 15, so I want the rest to be NA (or 0).

Min Reprex:

mygrid <- expand.grid(x=1:5,y=1:5) #Make a 5x5 grid
mygrid <- mygrid[sample(nrow(mygrid), 15),] #Randomly take 15 rows of the 25
mygrid$value <- LETTERS[1:15] #Assign them a letter
colnames(mygrid) <- c("row","col","value")

So if mygrid has "F" in the value column, and row=1, col=1....then I'd want [1,1] of a 5x5 matrix to be labeled "F". And the unknowns to be NA or zero.

The complete() function from tidyr can help you do this.

mygrid <- expand.grid(x=1:5,y=1:5) #Make a 5x5 grid
mygrid <- mygrid[sample(nrow(mygrid), 15),] #Randomly take 15 rows of the 25
mygrid$value <- LETTERS[1:15] #Assign them a letter
colnames(mygrid) <- c("row","col","value")
mygrid
#>    row col value
#> 3    3   1     A
#> 15   5   3     B
#> 18   3   4     C
#> 5    5   1     D
#> 9    4   2     E
#> 7    2   2     F
#> 11   1   3     G
#> 22   2   5     H
#> 13   3   3     I
#> 19   4   4     J
#> 10   5   2     K
#> 23   3   5     L
#> 16   1   4     M
#> 4    4   1     N
#> 2    2   1     O
Completed <- tidyr::complete(mygrid, row, col)
MAT <- matrix(Completed$value, nrow = 5, ncol = 5, byrow = TRUE)
MAT
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,] NA   NA   "G"  "M"  NA  
#> [2,] "O"  "F"  NA   NA   "H" 
#> [3,] "A"  NA   "I"  "C"  "L" 
#> [4,] "N"  "E"  NA   "J"  NA  
#> [5,] "D"  "K"  "B"  NA   NA

Created on 2022-05-02 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.