![](/img/trans.png)
[英]How can I count the number of elements in a vector that fall within a particular range using r?
[英]How can I create a for-loop to count the number of values within a vector that fall between a set boundary?
我试图通过简单地从每个索引中添加和减去一个设置值来设置向量的上下边界。 然后,我想创建一个循环,告诉我向量中的每个值(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,...)
您是否正在寻找这样的东西? 您的代码不正确,因为您的语法不正确。
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
编辑:在代码中添加注释以说明其功能。
在for
循环中,我们可以循环遍历v
每个元素,创建范围(-3,+3)并检查v
多少元素属于该范围,并将结果存储在新向量vec2
。
vec2 <- numeric(length = length(v))
for (i in seq_along(v)) {
vec2[i] <- sum((v >= v[i] - 3) & (v <= v[i] + 3))
}
vec2
#[1] 3 4 4 4 4 3 3 1
但是,您可以通过使用mapply
来避免for
循环
mapply(function(x, y) sum(v >= y & v <= x), v + 3, v - 3)
#[1] 3 4 4 4 4 3 3 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.