0

I have used a table (23 rows) where I extracted 2 columns (called them x and y) and named z=x-y and w=x-y. I also have a column called "type" which has 2 variables, "buy" or "sell".

I have an "ifelse" statement which states: If (type=="buy", z, w)

So, if i=1, type=buy, i want R to return z[[1]], i.e. the 1st answer from i=1 (not 23 answers for i=1). However, when I wrote down the loop, it returns 23 results for each "i". (i.e. for i=1, it returns 23 results for i=1). I have tried using the [[i]] brackets but still no result.

for(i in 1:23)
{
  z[i]=y[i]-x[i]
  w[i]=x[i]-y[i]
  ifelse(type[i]=="buy", z[i], w[i])
}

Code without the for loop:

z=y-x #buy
w=x-y #sell
ifelse(type=="buy",z, w)

Any advice? Thank you

  • I don't quite understand why the second version is not what you want. Also, I don't see any `if` statement in your code, only an `ifelse` statement. Or any nested loop? –  Apr 12 '18 at 17:27
  • 1
    Welcome to you. Please give a minimal example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example , https://stackoverflow.com/help/mcve – denis Apr 12 '18 at 17:28
  • @dash2 because it returns 23x23 answers. I want the code to return the 1st result for i=1, the 2nd for i=2 and so forth. By nested, I mean the vectors are nested so if i do z[1] it will return the 1st 23 results. If i type z[[1] still the same – Dena Christofidou Apr 12 '18 at 17:35
  • OK. Edit the question to make it clear what you are trying to achieve. –  Apr 12 '18 at 17:37

1 Answers1

0

The problem is that ifelse is vectorized. You need to use

if(type[i] == buy) z[i] else w[i]

instead of ifelse within the for loop. That said, the 2nd version is going to be much faster and cleaner in R. I would strongly recommend you use the vectorized method.

Melissa Key
  • 4,476
  • 12
  • 21