首页 > 解决方案 > 如何创建一个 for 循环来计算向量中位于设定边界之间的值的数量?

问题描述

我试图通过简单地从每个索引中添加和减去一个设定值来设置向量的上限和下限。然后我想创建一个循环,告诉我对于向量中的每个值 (i),向量中有多少其他点落在该边界内。

本质上是根据有多少值落在既定范围内来创建伪密度计算。

我有包含随机值的向量“v”。然后我添加/减去三个以获得上限和下限。但是不能创建一个循环来计算该向量中有多少其他值落在其中。

v <- c(1, 3, 4, 5, 8, 9, 10, 54)

for (i in v){
  vec2 <- (vec +3 > vec[i] & vec -3 < vec[i])
  }
vec2

我从这段代码中得到了 NA。

我也尝试过索引 vec +/- 3,但它也没有工作。

vec2 <- (vec[i] +3 > vec[i] & vec - 3 < vec[i))

我想要的是对于向量中的每个“i”值,我想知道有多少点落在该值 + 和 -3 内。

即第一个值为1:因此上限为4,下限为-2。我希望它计算向量中剩余的值有多少,落在这个范围内。第一个索引为 3(如果它包含自身)。

vec2 = (3, 4, 3, ...)

标签: rloopsfor-loop

解决方案


你在寻找这样的东西吗?您的代码不起作用,因为您的语法不正确。

vec <- c(1, 3, 4, 5, 8, 9, 10, 54) #Input vector

countvalswithin <- vector() #Empty vector that will store counts of values within bounds

#For loop to cycle through values stored in input vector
for(i in 1:length(vec)){
  currval <- vec[i] #Take current value
  lbound <- (currval - 3) #Calculate lower bound w.r.t. this value
  ubound <- (currval + 3) #Calculate upper bound w.r.t. this value

  #Create vector containing all values from source vector except current value
  #This will be used for comparison against current value to find values within bounds.
  othervals <- subset(vec, vec != currval)

  currcount <- 1 #Set to 0 to exclude self; count(er) of values within bounds of current value

  #For loop to cycle through all other values (excluding current value) to find values within bounds of current value
  for(j in 1:length(othervals)){

    #If statement to evaluate whether compared value is within bounds of current value; if it is, counter updates by 1
    if(othervals[j] > lbound & othervals[j] <= ubound){
      currcount <- currcount + 1 
    }

  }

  countvalswithin[i] <- currcount #Append count for current value to a vector

}

df <- data.frame(vec, countvalswithin) #Input vector and respective counts as a dataframe

df

 #    vec countvalswithin
 #  1   1               3
 #  2   3               4
 #  3   4               3
 #  4   5               4
 #  5   8               3
 #  6   9               3
 #  7  10               3
 #  8  54               1

编辑:在代码中添加了注释来解释它的作用。


推荐阅读