replace the NAs with the formula (df is your data.frame):
nas <- is.na(df$total)
df[nas, "total"] <- df$quantity[nas] * df$unitcost[nas] + df$tax[nas]
nas is a logical vector that indicates whether the total is missing.
EDIT
I guess you're trying to achieve this for any of the four components?
df
quantity unit_cost tax total
1 1 1 1 NA
2 2 2 2 NA
3 NA 3 3 4
4 1 NA 4 6
5 2 NA 5 9
for(x in c("quantity", "unit_cost", "tax", "total") ){
nas <- is.na(df[[x]])
df[nas,x] <- with(df, switch(x,
quantity= (total - tax)/unit_cost ,
unit_cost= (total - tax)/quantity,
tax= total - quantity*unit_cost,
total= tax + quantity*unit_cost
))[nas]
}
quantity unit_cost tax total
1 1.0000000 1 1 2
2 2.0000000 2 2 6
3 0.3333333 3 3 4
4 1.0000000 2 4 6
5 2.0000000 2 5 9
mind you this solution assumes that there is only one missing value in the 4 variables at each row, otherwise the calculation wouldn't be possible.
data
df <- data.frame(
quantity = c(1, 2, NA, 1, 2),
unit_cost = c(1,2,3,NA, NA),
tax = c(1,2,3,4,5),
total = c(NA,NA,4,6,9)
)