问题描述
我想每次在矩阵行中将值在给定范围内时都进行计数,然后对这些逻辑结果求和以得出每一行的一致性度量"./p>
可复制的示例:
m1<-matrix(c(1,2,1,6,3,7,4,2,6,8,11,15),ncol = 4,byrow = TRUE)#预期结果,每边均在+/- 1范围内exp.outcome< -matrix(c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE),ncol = 4,byrow = TRUE)
在每个值都位于该行中任何其他值的+/- 1范围内的情况下,我已经指出了预期的结果.
在 m1
的第一行中,第一个值(1)在该行中任何其他值的+/- 1之内,因此等于 TRUE
,依此类推.
相比之下, m1
的第4行中的任何值都不在彼此的单个数字值之内,因此每个值都被分配为 FALSE
.
任何指针将不胜感激?
更新:
借助所提供的帮助,我现在可以计算任意任意大矩阵(使用二项式系数,k从n中抽取,无需替换)满足上限条件的唯一值对.
在回答之前,我只是想澄清一下,在您的问题中您已经说过:
但是
>>m1 [1,4][1] 6
6不在1的+/- 1范围内,并且您的答案中有 FALSE
值是正确的结果.
解决方案
此解决方案应使您获得所需的结果:
t(apply(X = m1,#从矩阵中取出每一行保证金= 1,FUN =函数(x){sapply(X = x,#现在遍历该行的每个元素FUN =函数(y){#您的条件y%in%c(x-1)|y%in%c(x + 1)})}))
结果
[,1] [,2] [,3] [,4][1,]是是是否[2,]是否是是[3,] FALSE FALSE FALSE FALSE
检查
用于存储为 res
的结果.
>>相同(res,exp.outcome)[1]是
I would like to tally each time a value lies within a given range in a matrix by-row, and then sum these logical outcomes to derive a "measure of consistency" for each row.
Reproducible 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've indicated the the expected outcome, in the case where each value lies within +/- 1 range of any other values within that row.
Within the first row of m1
the first value (1) is within +/-1 of any other value in that row hence equals TRUE
, and so on.
By contrast, none of the values in row 4 of m1
are within a single digit value of each other and hence each is assigned FALSE
.
Any pointers would be much appreciated?
Update:
Thanks to the help provided I can now count the unique pairs of values which meet the ceiling criteria for any arbitrarily large matrix (using the binomial coefficient, k draws from n, without replacement).
Before progressing with the answer I just wanted to clarify that in your question you have said:
However,
>> m1[1,4]
[1] 6
6 is not within the +/- 1 from 1, and there is FALSE
value as a correct result in your answer.
Solution
This solution should get you to 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 stored as res
.
>> identical(res, exp.outcome)
[1] TRUE
这篇关于按矩阵计算在上限范围内的N次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!