0

I'm looking for a general way to do the following, I have a triangular matrix of nxn, for example:

a NA NA
b  d NA
c  e f

and convert it in:

a d f
b e NA
c NA NA

The idea is: for each column move the values, until the first non-NA value is in the first row

I imagine that it is done with a for, for each column, so that it goes up, but I do not know how to make it ...

Beth
  • 127
  • 6
  • It's a good idea to be more precise about this "going up". The first column shifts by one position, while the second one by two. Is it about shifting until the first non-NA value? – Julius Vainora May 31 '19 at 23:02
  • I'm sorry, I'll edit my question and yes, it's about that – Beth May 31 '19 at 23:09

2 Answers2

2

Here's a way with a custom function -

m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L, 
3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

custom_shift <- function(x) {
  y <- x[!is.na(x)]
  length(y) <- length(x)
  y
}

apply(m, 2, function(a) custom_shift(a))

     V1  V2  V3 
[1,] "a" "d" "f"
[2,] "b" "e" NA 
[3,] "c" NA  NA 
Shree
  • 10,835
  • 1
  • 14
  • 36
  • but I only have the matrix, no the vector – Beth May 31 '19 at 23:15
  • Both, input `m` and output, in my solution are matrix. I am not using any vector. Just run the code and let me know. – Shree May 31 '19 at 23:15
  • I found this, thank u :) https://stackoverflow.com/questions/3823211/convert-a-matrix-to-a-1-dimensional-array – Beth May 31 '19 at 23:17
0

Edit: Fixed it to not sort the values:

apply(m, 2, function(x) x[order(is.na(x))])

Original: Another solution which uses sort(..., na.last = T) and is good if you need each column to be sorted:

m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L, 
                                                                     3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

apply(m, 2, sort, na.last = T )

     V1  V2  V3 
[1,] "a" "d" "f"
[2,] "b" "e" NA 
[3,] "c" NA  NA 
Cole
  • 11,130
  • 1
  • 9
  • 24
  • by sorting, you are changing the order in which they appear. Although am not quite sure whether that is an issu – Onyambu Jun 01 '19 at 00:32
  • Isn't that the desired output? At the very least, it matches OP's second table. However, I agree that I wouldn't want to change the order as at that point, why have the matrix if the column row order doesn't matter? – Cole Jun 01 '19 at 00:50
  • 1
    this case it is matching because d – Onyambu Jun 01 '19 at 00:53
  • Oh I see. Yeah, you're right. I'll work on an edit or delete. – Cole Jun 01 '19 at 00:58
  • Thanks for pointing it out. I fixed it to sort on whether it's NA or not. This shouldn't change the order. – Cole Jun 01 '19 at 12:19