Home > Back-end >  How to create a vector from 2 merged matrices in R and fill in any dimension gaps with NA's?
How to create a vector from 2 merged matrices in R and fill in any dimension gaps with NA's?

Time:10-29

Suppose I have a 4x4 matrix generated as shown in the image below for mat1. (Image is from a snapshot of R Studio Console). Suppose I have another matrix generated of any size for example (1x2 in the below image for mat2). (In my code, the matrix elements and dimensions vary for both of the above matrices based on user inputs; though columns are only generated in multiples of 2, so I can have a [ ]x2 matrix, [ ]x4, [ ]x6, etc., and number of rows can be any integer).

In my code these 2 matrices are merged into a vector (a vector is required for processing via R package shinyMatrix).

Since these 2 matrix dimensions are variable, there are instances when merging the 2 matrices into a vector where you don't end up with the correct number of elements for converting back to a "dimensionable" matrix. As shown in the below image for mat3, where there are 18 elements after combining the 2 matrices mat1 and mat2 and certain elements must be dropped and NA's inserted to end up with a 4x4, 16 element matrix in this example.

There are instances where mat2 can have more elements than mat1. In this example I show mat1 with 16 elements and mat2 with 2 elements.

Importantly, in the code only the first 2 columns of mat1 can ever be replaced in this way with mat2 values. Columns 3 of mat1 are never changed by mat2.

Is there an efficient way to code this? Where you fit 2 matrices together into the dimensions of the larger matrix, and fill in any missing elements with NA?

I'm going down the path of measuring the length of mat1 columns 1 and 2, measuring the length of mat2 columns 1 and 2, merging, replacing elements, etc., but with my limited experience it's looking very cumbersome and not working quite right. I bet R has a slick way to accomplish this sort of thing. One of the apply functions, like mapply? I read somewhere mapply is great for subsetting matrices.Tibbles?

Here are my matrix inputs for the below image:

mat1 <- matrix(c(1,2,NA,NA, 3,4,NA,NA, 5:12), ncol = 4)
mat2 <- matrix(c(10,30), ncol = 2)
mat3 <- c(mat2,mat1)

enter image description here

CodePudding user response:

Based on the expected output, we may select the columns in 'mat1', that doesn't have anyNA and concatenate (c) with the length corrected columns by appending NA at the end in 'mat2'

c(sapply(mat2, `length<-`, nrow(mat1)), mat1[,!apply(mat1, 2, anyNA)])
[1] 10 NA NA NA 30 NA NA NA  5  6  7  8  9 10 11 12
  • Related