lundi 8 mai 2017

R: if statement in zoo series when adding a column

I have the following zoo series:

head(prices.zoo)

         JetFuel HeatingOil  Spread
Sep 1996   0.682     0.6794  0.0026
Oct 1996   0.703     0.7307 -0.0277
Nov 1996   0.696     0.7261 -0.0301
Dec 1996   0.693     0.7171 -0.0241
Jan 1997   0.680     0.7142 -0.0342
Feb 1997   0.619     0.6081  0.0109

My goal is to add a 4th column Action that has 1 when Spread>0 and -1 when Spread<0. I tried the following code:

f <-function(x){ 
if(x>0) y=1 
else y= -1
return(y)}

prices.zoo$Action <- sapply(prices.zoo$Spread,f)

A warning message popped up: "Warning message: In if (x > 0) y = 1000 else y = -100 : the condition has length > 1 and only the first element will be used" And the result is obviously not correct:

         JetFuel HeatingOil  Spread Action
Sep 1996   0.682     0.6794  0.0026      1
Oct 1996   0.703     0.7307 -0.0277      1
Nov 1996   0.696     0.7261 -0.0301      1
Dec 1996   0.693     0.7171 -0.0241      1
Jan 1997   0.680     0.7142 -0.0342      1
Feb 1997   0.619     0.6081  0.0109      1

But after I converted the zoo series to a data frame, everything worked:

prices.zoo.df <- data.frame(prices.zoo)
prices.zoo.df$Action <- sapply(prices.zoo.df$Spread,f) 
head(prices.zoo.df)

         JetFuel HeatingOil  Spread Action
Sep 1996   0.682     0.6794  0.0026      1
Oct 1996   0.703     0.7307 -0.0277     -1
Nov 1996   0.696     0.7261 -0.0301     -1
Dec 1996   0.693     0.7171 -0.0241     -1
Jan 1997   0.680     0.7142 -0.0342     -1
Feb 1997   0.619     0.6081  0.0109      1

Could anyone please explain to me why this is the case? Is there any way to achieve the same thing on the zoo series without moving to the data frame? Thank you.

Aucun commentaire:

Enregistrer un commentaire