如何创建for循环来计算向量中位于集合边界之间的值的数量?
我试图通过简单地从每个索引中加上和减去一个设定值来设置向量的上下限。然后我想创建一个循环,告诉我向量中的每个值(I),向量中还有多少其他点落在该边界内 基本上是根据多少值落在确定的范围内创建伪密度计算 我的向量“v”包含随机值。然后我加/减三,得到上限和下限。但不能创建一个循环来计算该向量中有多少其他值属于该循环如何创建for循环来计算向量中位于集合边界之间的值的数量?,r,loops,for-loop,R,Loops,For Loop,我试图通过简单地从每个索引中加上和减去一个设定值来设置向量的上下限。然后我想创建一个循环,告诉我向量中的每个值(I),向量中还有多少其他点落在该边界内 基本上是根据多少值落在确定的范围内创建伪密度计算 我的向量“v”包含随机值。然后我加/减三,得到上限和下限。但不能创建一个循环来计算该向量中有多少其他值属于该循环 v <- c(1, 3, 4, 5, 8, 9, 10, 54) for (i in v){ vec2 <- (vec +3 > vec[i] & ve
v <- c(1, 3, 4, 5, 8, 9, 10, 54)
for (i in v){
vec2 <- (vec +3 > vec[i] & vec -3 < vec[i])
}
vec2
v你在找这样的东西吗?您的代码无法工作,因为您的语法不正确
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
vec在您的for
循环中,我们可以循环v
中的每个元素,创建范围(-3,+3),检查v
中有多少元素在该范围内,并将结果存储在新的vectorvec2
中
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
是的,太好了。非常感谢。我肯定需要更多的循环练习。你能解释一下“if”的作用吗(不带“else”语句?我在代码中添加了解释性注释。这里不需要else
子句,因为你只关心值是否在范围内(即else
条件是隐式的和不相关的)。
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(function(x, y) sum(v >= y & v <= x), v + 3, v - 3)
#[1] 3 4 4 4 4 3 3 1