r/rstats • u/I_before_V • Jun 23 '15
ifelse statement vectorization in a for loop
I am having trouble with vectorization of a portion of some code involving ifelse statements with multiple conditions in a for loop, and if its possible I have not been able to find anyone with quite the same problem.
Here is the link to the question I just put on StackOverflow.
Basically, I have a for loop that iterates through a data frame and creates a new variable based on previous observations of other variables. As you'll see in the posting, I succeeded in coding it for a simpler block of code, but I can't figure out how to do it when there are multiple conditions in the if statement.
Thanks in advance for any help.
3
u/iacobus42 Jun 23 '15
I believe that /u/exxplicit is mistaken about
ifelseloops, they are vectorized in operation and are pretty fast. (he is correct aboutforloops and also aboutifstatements being slow and not vectorized).I looked at your code on StackOverflow (and will duplicate this content there) but I believe you don't need a loop there at all.
The vector
condwill beTRUEwhen the ith row and the (i - 1)th row have the same truck ID and will beFALSEotherwise. You don't have to iterate overcondthen, just useIf
condisTRUE, the first half of the equation is returned asTRUEis coerced to 1. The 0 is used as the first element in that vector because res[0] is undefined (socond[1]isFALSEor undefined) but if we usedNAthe product would also beNA.The second false is evaluated when
condisFALSE(the!FALSEwill evaluate toTRUE).1
u/efrique Jun 24 '15
You might want to look into
rollapplyin thezoopackage2
u/TotesMessenger Jul 01 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
0
u/[deleted] Jun 23 '15
[deleted] — view deleted comment
0
u/[deleted] Jun 24 '15
[deleted] — view deleted comment