lundi 26 juin 2017

Replacing 0 in particular order using nested if and for loop in r

i'm trying to solve the following by using for and nested if in r: my data for price available is: test2

[1]   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   
0 0   0   0   0 
[24]   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   
0   0   0   0   0
[47]   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0 
399   0   0 399   0
[70]   0   0   0 399   0   0   0   0 429   0 429   0   0   0 499   0 429   0   
0   0   0   0 529
[93]   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   
0   0   0   0   0
[116]   0   0   0   0   0   0   0   0   0   0   0   0   0   0

the problem: to replace 0 before the 1st occurrence of price with value of the 1st occurrence, then replace 0 after 1st occurrence with the value of 1st occurrence until 2nd occurrence of price and so on. The 0 after last occurrence of price should be replaced with the value of last occurrence.

I have used the following code:

priceposition2 <- which(test2>0)
for(i in 1:length(priceposition2)){
for(m in 1:length(test2)){
  if (m <= priceposition2[1]){
test2[m] <- test2[priceposition2[1]]
} else if (m > priceposition2[1]){
  if (m> priceposition2[i] && m < priceposition2[i+1]){
    test2[m] <- test2[priceposition2[i]]

  }else if(m> priceposition2[length(priceposition2)]){
    test2[m] <- test2[priceposition2[length(priceposition2)]]
  }

}
m=m+1
}
 i=i+1
}

I get the following result after this:

[1] 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 
399 399 399 399 399
[24] 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 
399 399 399 399 399
[47] 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 399 
399 399 399 399 399 399
[70] 399 399 399 399 399 399 399 399 429 429 429 429 429 429 499 499 429 429 
429 429 429 429 529
[93] 529 529 529 529 529 529 529 529 529 529 529 529 529 529 529 529 529 529 
529 529 529 529 529
[116] 529 529 529 529 529 529 529 529 529 529 529 529 529 529

which is exactly what i want. The problem is i get error by using the above code:

Error in if (m > priceposition2[i] && m < priceposition2[i + 1]) { : 
 missing value where TRUE/FALSE needed

Is there something that i'm doing wrong? Also is there an alternative using apply family for the above problem?

Aucun commentaire:

Enregistrer un commentaire