[英]If-else statement in R coding did not work
I did coding in R as below,我在 R 中进行了编码,如下所示,
data1<-c(25,35,60,79,50)
data2<-c(100,150,170,200,1000)
g1=sort(data1)
g2=sort(data2)
ybar1<-mean(g1)
ybar2<-mean(g2)
#BIWEIGHT
med1=median(g1)
med2=median(g2)
mad1=1.4826*(median(abs(g1-med1)))
mad2=1.4826*(median(abs(g2-med2)))
u1=(g1-med1)/(9*mad1)
u2=(g2-med2)/(9*mad2)
#cat("\nu1:",u1)
u=rbind(u1,u2)
print(u)
abs=abs(u)
print(abs)
for(j in abs){
if(j < 1){
num1 = ((g1-med1)^2)*((1-(u1^2))^4)
den1 = ((1-(u1^2))*(1-5*(u1^2)))
num2 = ((g2-med2)^2)*((1-(u2^2))^4)
den2 = ((1-(u2^2))*(1-5*(u2^2)))
}
}
cat("\num2:",num2)
but when i calculate manually, for data1, every value u1 is less than 1, thus the coding is right with my manual calculation, but for data2, it include value of u2 that is more than 1. can anyone help me figure out why it happen and how to fix it?但是当我手动计算时,对于 data1,每个值 u1 都小于 1,因此编码与我的手动计算是正确的,但是对于 data2,它包含大于 1 的 u2 值。谁能帮我弄清楚为什么发生以及如何解决? thankyou in advance.先感谢您。
The problem seems to me that within the if
condition (and therefore also within the for
loop), you always take the entire vectors ( g1
, g2
, u1
, u2
).在我看来,问题是在if
条件中(因此也在for
循环中),您总是采用整个向量( g1
、 g2
、 u1
、 u2
)。 You do not tell R to only use those values in g1 and g2 for which j<1.您不会告诉 R仅使用g1 和 g2 中 j<1 的那些值。 Instead you use the entire vector as many times as there are values in abs
that are <1.相反,您使用整个向量的次数与abs
中小于 1 的值一样多。
Furthermore, you combine u1
and u2
as a 2-row matrix, but leave g1 and g2 separate.此外,您将u1
和u2
组合为一个 2 行矩阵,但将 g1 和 g2 分开。 This is confusing and gets you more problems.这令人困惑,并且会给您带来更多问题。 I suggest you do separate loops for the two vectors.我建议你为两个向量做单独的循环。
You can do that as follows:你可以这样做:
idx1 <- which(abs(u1) < 1) #Gives you the indexes/positions in vector u1, where abs(u1)<1 is TRUE
idx2 <- which(abs(u2) < 1) #same for u2
for(i in idx1){
num1[i] = ((g1[i]-med1)^2)*((1-(u1[i]^2))^4)
den1[i] = ((1-(u1[i]^2))*(1-5*(u1[i]^2)))
}
for(j in idx2){
num2[j] = ((g2[j]-med2)^2)*((1-(u2[j]^2))^4)
den2[j] = ((1-(u2[j]^2))*(1-5*(u2[j]^2)))
}
This way, num1
and den1
have 5 elements because all absolute values of u1 are <1.这样, num1
和den1
有 5 个元素,因为 u1 的所有绝对值都 <1。
In contrast, num2
and den2
have 4 elements, because the last value of u2 is ca.相比之下, num2
和den2
有 4 个元素,因为 u2 的最后一个值是 ca。 2.07. 2.07.
Hopefully, this helps you.希望这对您有所帮助。
EDIT: Forgot to add the indices ( [i] and [j]
) to num1
/ 2
and den1
/ 2
.编辑:忘记将索引( [i] and [j]
)添加到num1
/ 2
和den1
/ 2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.