Moving Positions in a Table - R

In R, given the common matrix A, how can I move the triangle NA to a position in matrix B? And if the matrix is ​​mxn?

> A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
> A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3


> B <- matrix(c(3, 2, 3, 4, 5, NA, 1, NA, NA), nrow = 3)
> B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA

Thank!

+4
source share
2 answers

I don’t know if there is a more idiomatic way, but it looks like what you want:

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
A

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA

A <- matrix(c(3, NA, NA, NA, 4, 2, NA, NA, 1, 5, 3, NA), nrow=4)
A

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3
[4,]   NA   NA   NA


t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
[4,]   NA   NA   NA

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3, 6, 7, 8), nrow=3)
A

     [,1] [,2] [,3] [,4]
[1,]    3    4    1    6
[2,]   NA    2    5    7
[3,]   NA   NA    3    8

t(apply(A, 1, function(x) x[order(is.na(x))]))

     [,1] [,2] [,3] [,4]
[1,]    3    4    1    6
[2,]    2    5    7   NA
[3,]    3    8   NA   NA
+5
source

A possible way is to rotate 180 columns. I suggested that the triangle NA of A is used to set NA in matrix B after rotation. You can use the same technique to rotate in matrix A.

A <- matrix(c(3, NA, NA, 4, 2, NA, 1, 5, 3), nrow = 3)
A
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]   NA    2    5
[3,]   NA   NA    3

B <- matrix(c(3, 2, 3, 4, 5, 4, 1, 6, 8), nrow = 3)
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5    6
[3,]    3    4    8

#Find NA in A
NA_Val <- is.na(A)

#Rotate NA matrix on column
NA_VAL_180 <- NA_Val[1:nrow(NA_Val),ncol(NA_Val):1]

#Set corresponding values NA in B. 
B[NA_VAL_180] <- NA
B
     [,1] [,2] [,3]
[1,]    3    4    1
[2,]    2    5   NA
[3,]    3   NA   NA
+1
source

Source: https://habr.com/ru/post/1690456/


All Articles