2

I have a table (no header) in R:

1 1 1 0 0
1 1 1 0 0
0 0 0 1 1

What I want to do is extract continuous 1s from every row and column to later on make a string with these 1s and finally convert the string to an integer from binary.

Example, say I extract the continuous 1s from row 1 -> 1 1 1, then I make a string from these 1s, and finally convert this string which is a binary value to a n integer, the outcome should be 7.

Thank you.

Tripon
  • 81
  • 1
  • 10

1 Answers1

0

If you can assume that you just have contiguous 1s with no 1s elsewhere, you can do something like this:

2 ^ rowSums(tab) - 1

For example:

tab <- as.table(matrix(c(1,1,1,0,0,1,1,1,0,0,0,0,0,1,1), nrow = 3, byrow = T))
2 ^ rowSums(tab) - 1
# A B C
# 7 7 3

If you do not have this contiguity assumption, us the run-length encoding:

-1 + 2 ^ apply(tab, 1, function(x) max(rle(x)$lengths[rle(x)$values == 1]))

Then the example is

tab <- as.table(matrix(c(0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1), nrow = 3, byrow = T))

#   A B C D E F
# A 0 1 1 1 0 0
# B 0 1 1 1 0 0
# C 0 0 0 0 1 1 

and the above again yields

# A B C
# 7 7 3
Robert Krzyzanowski
  • 9,294
  • 28
  • 24