Одним из способов написания функции может быть
remove_warehouse <- function(df, product_id, amount) {
id = df$product_id == product_id
if (any(id))
amount_base = df$amount[id]
else
stop("No id present")
if (amount > amount_base)
stop("No sufficient amount")
else
df$amount[id] = df$amount[id] - amount
df
}
remove_warehouse(df, 4911, 90)
# product_id amount
#1 1001 1
#2 4911 10
#3 4014 32
remove_warehouse(df, 1234, 12)
#Error in remove_warehouse(df, 1234, 12) : No id present
remove_warehouse(df, 1001, 100)
#Error in remove_warehouse(df, 1001, 100) : No sufficient amount
Это предполагает, что у вас будет только один product_id
в ваших df
.
данных
df <- structure(list(product_id = c(1001L, 4911L, 4014L), amount = c(1L,
100L, 32L)), .Names = c("product_id", "amount"), class = "data.frame",
row.names = c("1", "2", "3"))