Here is a vector solution using the tidyr package.
set.seed(123)
The strategy was to convert the source data to a wide format, where the rows were the product identifier and the columns were weeks. Then split the data frames into each other. Convert back to a long format and add the newly computed values ββto the exampleData data frame. This works, not very clean, but much faster than a loop. The dplyr package is another tool for this kind of work.
To compare the results of this code with you, use a test case:
print(identical(goldendata, exampleData))
If goldendata is your good results, be sure to use the same random numbers with the set.seed () function.
source share