I have data in columns which I need to do calculations on. Is it possible to do this using previous row values without using a loop? E.g. if in the first column the value is 139, calculate the median of the last 5 values and the percent change of the value 5 rows above and the value in the current row?
ID Data PF 135 5 123 136 4 141 137 5 124 138 6 200 139 1 310 140 2 141 141 4 141 So here in this dataset you would do:
- Find
139inIDcolumn - Return average of last 5 rows in
Data(Gives4.2) - Return performance of values in
PF5 rows above to current value (Gives152%)
If I would do a loop it looks like this:
for (i in 1:nrow(data)){ if(data$ID == "139" & i>=3) {data$New_column <- data[i,"PF"] / data[i-4,"PF"] - 1 } The problem is that the loop takes too long due to to many data points. The ID 139 will appear several times in the dataset.
Many thanks. Carlos
rollapplyin thezoopackage.