Reputation: 7005
> w
A B
1998-01-08 -0.0051653999 0.007
1998-01-09 0.0064191599 -0.008
1998-01-12 -0.0018169993 0.009
1998-01-13 0.0046482541 -0.005
1998-01-14 0.0080997329 -0.006
1998-01-15 -0.0007764179 0.008
c<-(-0.5,-0.6,-0.7,0.1,0.2,0.3)
I want to create a matrix with one column that selects A or B from w conditional on whether c > 0
i.e.
w[,if (c<0) A else B]
C
1998-01-08 -0.0051653999
1998-01-09 0.0064191599
1998-01-12 -0.0018169993
1998-01-13 -0.005
1998-01-14 -0.006
1998-01-15 0.008
Upvotes: 0
Views: 2736
Reputation: 61154
You missed c
function for concatenating the vector (-0.5,-0.6,-0.7,0.1,0.2,0.3)
, I used ind
as the name for that vector. Then indexing can be done using ifelse
function as in:
> ind <-c(-0.5,-0.6,-0.7,0.1,0.2,0.3)
> data.frame(C=ifelse(ind<0, w$A, w$B), row.names=rownames(w))
C
1998-01-08 -0.005165400
1998-01-09 0.006419160
1998-01-12 -0.001816999
1998-01-13 -0.005000000
1998-01-14 -0.006000000
1998-01-15 0.008000000
Upvotes: 1
Reputation: 4598
Try looking at this Extract matrix column values by matrix column name In short, I think you want to try this command: if(c<0) w[,"A"] else w[,"B"]
Upvotes: 0