-4

I have an array with size 31x36 in R called input_matrix. In each row of that matrix there are 16 non-zero values and 20 zero value. The indexes of non-zero values and zero values for each row are different. I want to retrieve as a final output of my system a matrix output_matrix with size 31x16 which contains the only non-zero values. An one-row example, if I have:

5 0 4 0 4 0 1 0 0 0 .. 1

I want to retrieve: (5 4 4 1 ... 1). How can I do so in R?

smci
  • 32,567
  • 20
  • 113
  • 146
Jose Ramon
  • 5,572
  • 25
  • 76
  • 152
  • Essentially duplicate of [Adding non-zero elements of a matrix in R](https://stackoverflow.com/questions/28968848/adding-non-zero-elements-of-a-matrix-in-r). You just want `m[m != 0]` – smci Jan 13 '18 at 23:00
  • I assume you want to keep the order of the numbers intact? – s_baldur Jan 13 '18 at 23:05
  • 1
    Is there supposed to be "padding" (perhaps with `NA`'s) for rows whose non-zero counts are less than 16? – IRTFM Jan 13 '18 at 23:28
  • @snoram yes exactly the order needs to be the same. – Jose Ramon Jan 14 '18 at 15:23
  • @42- not sure what do you mean with your question, – Jose Ramon Jan 14 '18 at 15:24
  • @JoseRamon Ok, then it is not exactly a duplicate of the question smci linked to – s_baldur Jan 14 '18 at 15:25
  • 1
    If the number of non-zero items in each row varies then you cannot map it into a regular arrangement without padding at the end or beginning of each row. The multiple comments show that your question is unclear and it is unclear because there is no example data-object. – IRTFM Jan 14 '18 at 18:04

1 Answers1

1

It is always good to start with a reproducible example. So here is one:

# Create a matrix per the description
# fill first with random integers
input_matrix <- matrix(sample(1:9, size = 31L*36L, replace = TRUE), nrow = 31)
# Now add 20 zero value to each row randomly
for (i in 1:nrow(input_matrix)) {
  input_matrix[i, sample(1:36, size = 20)] <- 0L
} 

Solution 1

t(apply(input_matrix, 1, function(x) x[x != 0]))

Solution 2 (simplified version)

matrix(t(input_matrix)[t(input_matrix) != 0], nrow = 31, byrow = TRUE)
s_baldur
  • 29,441
  • 4
  • 36
  • 69