I have a data frame with 12 columns, and I need to perform some basic arithmetic on 7 of them: columns 5:12. The data frame, named test is pasted below.
The arithmetic I am looking to perform would change each element based on the previous element except for the first in each column as the arithmetic for the first element of each column is different than the subsequent elements. Also, the element vector would be changed by the equation as its original value is involved. I did the arithmetic for the first element in a previous line of code, so that's already the correct value.
Here is the math:
B = (1-.08)Bt + .08(z)
where Bt is the previous element's value and z is the current element's value. Each element will then become B.
EDIT: I probably wasn't clear, but Bt will be the newly calculated value of B from the previous element. So this has a step by step progression.
I've been attempting this with apply, but I'm confused because I've only done something similar on single vectors in the past with a for loop, but in that case, I created brand new vector elements based on previous elements, and like this example, the first element was pre-defined.
I can conceptualize this, but can't code it with my current skill set in R.
Any help is much appreciated. Thanks.
Data:
test <-
structure(list(Forecast_day = c(8, 8, 8, 8, 8, 8), Forecast_date = structure(c(17555,
17556, 17557, 17558, 17559, 17560), class = "Date"), DeliveryDate = structure(c(17563,
17564, 17565, 17566, 17567, 17568), class = "Date"), HourEnding = c(1L,
1L, 1L, 1L, 1L, 1L), Coast = c(-0.0459999999999999, -11.6, -3.8,
-7.09999999999999, -9.6, -11.2), East = c(0.01, -8.5, -1.5, -3.5,
-0.5, -9.5), FarWest = c(-0.07, -6.5, -9, -11.5, 6, -10.5), North = c(0.01,
-2.5, -1.5, -1.5, 14, 0), NorthCentral = c(-0.07, -7.25, -5.75,
-10.75, 6.75, 1.5), SouthCentral = c(-0.01, -10, -8.5, -3.5,
-8.5, -11), Southern = c(-0.04, -10.8, -4.6, -7.8, -9.6, -12),
West = c(-0.16, -7.4, -6.6, -13.2, 7.8, -9)), .Names = c("Forecast_day",
"Forecast_date", "DeliveryDate", "HourEnding", "Coast", "East",
"FarWest", "North", "NorthCentral", "SouthCentral", "Southern",
"West"), row.names = c(NA, -6L), class = "data.frame")

You can use the
Reducemeta-function to sequentially apply the arithmetic along a vector, using the previous result as one of the inputs.First, wrap the arithmetic in a function.
To do it for one column, use the function in
Reduceand setaccumulate = TRUEto keep each result.Use
lapplyto replace multiple columns at the same time.