R中xts对象上的条件语句

R中xts对象上的条件语句,r,xts,R,Xts,我在R中有一个xts对象,我想从中创建另一个对象。我的xts对象看起来像: dates = seq(from=as.Date('2012-09-01'),to=as.Date('2012-09-05'),'day') my_xts_obj = xts(c(1,2,3,4,5),dates) > my_xts_obj [,1] 2012-09-01 1 2012-09-02 2 2012-09-03 3 2012-09-04 4 2012-09-

我在R中有一个xts对象,我想从中创建另一个对象。我的xts对象看起来像:

dates = seq(from=as.Date('2012-09-01'),to=as.Date('2012-09-05'),'day')
my_xts_obj = xts(c(1,2,3,4,5),dates)
> my_xts_obj
           [,1]
2012-09-01    1
2012-09-02    2
2012-09-03    3
2012-09-04    4
2012-09-05    5
我想创建另一个满足以下条件的对象

val = 0, if my_xts_obj >2.5 and <3.5
val = -1, if my_xts_obj <2.5
val = +1, if my_xts_obj <3.5
我可以使用的一种方法是通过for循环解析它,使用if-then语句生成我的对象。有更好的办法吗

我能想到的另一种方法是

my_new_xts_obj = my_xts_obj%/%2.5 + my_xts_obj%/%3.5, gives me 
2012-09-01    0
2012-09-02    0
2012-09-03    1
2012-09-04    2
2012-09-05    3

这并不是我想要的

你可以通过子集轻松做到这一点:

x <- my_xts_obj
y <- x*0
y[x < 2.5] <- -1
y[x > 3.5] <- 1

通过子集设置,您可以轻松做到这一点:

x <- my_xts_obj
y <- x*0
y[x < 2.5] <- -1
y[x > 3.5] <- 1