I have this data frame showing similar data as BOM and I created a loop to find the accumulative prices of the items from A(raw material), B(sub-assembly) and to C(finished product).
df$final_price = 0
maxLevel <- max(df$productionlevel)
df[df$price != 0, 'final_price'] <- df[df$price != 0, 'quantity'] * df[df$price != 0, 'price']
for (level in (maxLevel - 1):0) {
condition <- df$productionlevel == level & df$itemtype != "A"
if (any(condition)) {
higherLevel <- level + 1
df[condition, 'final_price'] <- sum(df[df$productionlevel == higherLevel, 'final_price']) * df[condition, 'quantity']
}
}
I want to use the same logic as this loop but with a recursive function in R (tidyverse). Can anyone help?
If I run dput(df), This is the structure of my dataframe:
structure(list(item_id = c("i1", "i2", "i3", "i4", "i5", "i6",
"i7", "i8", "i9"), quantity = c(2, 2, 5, 1, 1, 2, 4, 1, 1), price = c(2,
5, 3, 7, 10, 0, 4, 0, 0), itemtype = c("A", "A", "A", "A", "A",
"B", "A", "B", "C"), productionlevel = c(3, 3, 3, 3, 2, 2, 1,
1, 0)), class = "data.frame", row.names = c(NA, -9L))
I want to use the same logic as this loop but with a recursive function in R (tidyverse) to find these accumulative costs. Can anyone help?