Counting N entries in the ceiling range of the matrix row

I would like to count every time a value is in a given range in a matrix row, and then sum these logical results to get a “measure of consistency” for each row.

Playable example:

m1 <- matrix(c(1,2,1,6,3,7,4,2,6,8,11,15), ncol=4, byrow = TRUE) # expected outcome, given a range of +/-1 either side exp.outcome<-matrix(c(TRUE,TRUE,TRUE,FALSE, TRUE,FALSE,TRUE,TRUE, FALSE,FALSE,FALSE,FALSE), ncol=4, byrow=TRUE) 

Above, I indicated the expected result, in the case when each value is within the +/- 1 range of any other values ​​inside this line.

In the first line of m1 first value (1) is within +/- 1 of any other value in this line, therefore, it is TRUE , etc.

In contrast, none of the values ​​in line 4 of m1 are within the same sign from each other, and therefore each is assigned FALSE .

Any pointers would be much appreciated?

Update:

Thanks to the help provided, I can now calculate unique pairs of values ​​that meet the ceiling criteria for any arbitrarily large matrix (using the binomial coefficient, k extracts from n without replacement).

Ball selection: drawing unsorted, without replacement.

+5
source share
2 answers

Before moving on to the answer, I just wanted to clarify what you said in your question:

In the first line of m1 first value (1) is within +/- 1 of any other value in this line, therefore, it is TRUE , etc.

but

 >> m1[1,4] [1] 6 

6 is not within +/- 1 of 1, and your answer has a value of FALSE .

Decision

This solution should give you the desired results:

 t(apply( X = m1, # Take each row from the matrix MARGIN = 1, FUN = function(x) { sapply( X = x, # Now go through each element of that row FUN = function(y) { # Your conditions y %in% c(x - 1) | y %in% c(x + 1) } ) } )) 

results

  [,1] [,2] [,3] [,4] [1,] TRUE TRUE TRUE FALSE [2,] TRUE FALSE TRUE TRUE [3,] FALSE FALSE FALSE FALSE 

Check

For results saved as res .

 >> identical(res, exp.outcome) [1] TRUE 
+3
source

Here's some neat basic R method that uses an array:

The first two lines are the settings that store a three-dimensional array of valid values ​​and a matrix that will save the desired result. The structure of the array is as follows: the columns correspond to the valid values ​​of the matrix element in the same column. The third dimension corresponds to the rows of the matrix.

Pre-allocation in this way should reduce recalculations.

 # construct array of all +1/-1 values valueArray <- sapply(1:nrow(m1), function(i) rbind(m1[i,]-1, m1[i,], m1[i,]+1), simplify="array") # get logical matrix of correct dimensions exp.outcome <- matrix(TRUE, nrow(m1), ncol(m1)) # get desired values for(i in 1:nrow(m1)) { exp.outcome[i, ] <- sapply(1:ncol(m1), function(j) m1[i, j] %in% c(valueArray[, -j, i])) } 

What returns

 exp.outcome [,1] [,2] [,3] [,4] [1,] TRUE TRUE TRUE FALSE [2,] TRUE FALSE TRUE TRUE [3,] FALSE FALSE FALSE FALSE 
+2
source

All Articles