0
> 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
ManInMoon
  • 6,795
  • 15
  • 70
  • 133

2 Answers2

1

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
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

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"]

Community
  • 1
  • 1
Andrew W
  • 4,530
  • 1
  • 16
  • 16
  • I used 1 and 2 instead but get this error:Warning message: In if (c <0) 1 else 2 : the condition has length > 1 and only the first element will be used – ManInMoon May 24 '13 at 13:43
  • @ManInMoon what you got is not an error, it's a warning, from the help of `if` you'll find the following: `Conditions of length greater than one are accepted with a warning, but only the first element is used.` Use `ifelse` instead, see [my answer](http://stackoverflow.com/questions/16736232/r-select-column-element-based-on-condition/16736468#16736468). – Jilber Urbina May 24 '13 at 13:55