I would like to make the code more efficient.
The example creates a vector (called ‘new_vector’). The values of this ‘new_vector’ are changed based on if/else-conditions that refer to the values of three other vectors of the same length.
If the conditions are fulfilled, the corresponding elements of the ‘new_vector’ are updated using values from one of the other vectors (in the example elements of M_date are written into new_vector).
Here is the example code:
new_vector<-c(9,9,9)
S_date<-c(1,1,as.Date('2010/08/01'))
V_date<-c(1,as.Date('2010/09/01'),1)
M_date<-c(2,as.Date('2010/07/01'),1)
for (i in 1:3) {
if ( (S_date[i]==1) & (V_date[i]==1 | M_date[i] < V_date[i]) ) {
new_vector[i]<-M_date[i]
}
}
The result of the example is:
> new_vector
[1] 2 14791 9
The example is simplified and in reality the vectors are larger and there are additional if/else-conditions.
How can I avoid the loop and use implicit methods for vector operations instead?
If you write the expression without the [i] bits you get a vector True/False result:
assign that to a vector, and replace in new_vector by that result:
Its a fairly general pattern. Compute a boolean vector, then replace those matching values with the corresponding values from another vector.
It works because the FALSE value in the third element of result means that
new_vector[3]doesn’t get touched.