I am trying to iterate through a vector and edit a new one however I keep getting the error replacement has length zero. The portion where the error occurs is here:
我试图迭代一个向量并编辑一个新的但我一直得到错误替换长度为零。发生错误的部分在这里:
NewPos1 = rep(NROW(sig_decision))
for( i in 2:length(NewPos)) {
NewPos1[i] = ifelse( NewPos[i] == 0 & NewPos[i-1] == 1 & ind1[i] > 0 , 1,
ifelse(NewPos[i] ==0 & NewPos[i-1] == -1 & ind1[i] < 0 , -1,0))
}
Ok to be more specific
好的更具体一点
Where am I going wrong?
我哪里错了?
Edit: I should be more specific ind1 is a numeric vector. The reason why I want a loop is so that starting with the 2nd element in NewPos1([NewPos[1]) if the previous element of NewPos(NewPos[1]) is 1 and ind1[2] > 0 then I want NewPos1[2] to be one and so forth iterating through the entire vector so that if ind1[3] is >0 then NewPos1[3] is also 1
编辑:我应该更具体ind1是一个数字向量。我想要一个循环的原因是从NewPos1中的第二个元素开始([NewPos [1])如果NewPos的前一个元素(NewPos [1])是1而ind1 [2]> 0那么我想要NewPos1 [ 2]迭代遍历整个向量,以便如果ind1 [3]> 0,那么NewPos1 [3]也是1
1 个解决方案
#1
3
The problem is very likely to lie with ind1
(since you haven't told us what that is). I'm guessing that (if ind1
is really a numeric vector the same length as NewPos
) this is a more efficient solution to your problem:
这个问题很可能与ind1有关(因为你没有告诉我们那是什么)。我猜测(如果ind1实际上是一个与NewPos长度相同的数字向量),这是一个更有效的解决方案:
v <- NewPos[-1] ## elements 2:n
ind2 <- ind1[-1] ## elements 2:n
vlag1 <- NewPos[-length(NewPos)] ## elements 1:(n-1)
NewPos1 <- ifelse(v==0 & vlag1==1 & ind2>0, 1,
ifelse(v==0 & vlag==-1 & ind2<0, -1, 0))
As @CarlWitthoft points out, switch
can sometimes be useful, but I don't think that two nested ifelse
statements is excessive.
正如@CarlWitthoft所指出的,切换有时可能很有用,但我不认为两个嵌套的ifelse语句过多。
#1
3
The problem is very likely to lie with ind1
(since you haven't told us what that is). I'm guessing that (if ind1
is really a numeric vector the same length as NewPos
) this is a more efficient solution to your problem:
这个问题很可能与ind1有关(因为你没有告诉我们那是什么)。我猜测(如果ind1实际上是一个与NewPos长度相同的数字向量),这是一个更有效的解决方案:
v <- NewPos[-1] ## elements 2:n
ind2 <- ind1[-1] ## elements 2:n
vlag1 <- NewPos[-length(NewPos)] ## elements 1:(n-1)
NewPos1 <- ifelse(v==0 & vlag1==1 & ind2>0, 1,
ifelse(v==0 & vlag==-1 & ind2<0, -1, 0))
As @CarlWitthoft points out, switch
can sometimes be useful, but I don't think that two nested ifelse
statements is excessive.
正如@CarlWitthoft所指出的,切换有时可能很有用,但我不认为两个嵌套的ifelse语句过多。