I apologize if the title may not be clear.
With
df <- data.frame(profit = c(1, 1, 0, 0, 0, -1),
offerA = round(rnorm(6), 2),
offerB = round(runif(6), 2),
offerC = sample(1:6))
df
profit offerA offerB offerC
1 1 -0.51 0.91 6
2 1 -0.03 0.75 4
3 0 -1.02 0.28 5
4 0 0.63 0.61 1
5 0 2.32 0.37 2
6 -1 -0.15 0.43 3
I need to add a field named bid depending on the value of profit under the following conditions:
with(df,
if (profit > 0) {
apply(cbind(offerA, offerB, offerC), 1, max)
}
else if (profit = 0) {
apply(cbind(offerA, offerB, offerC), 1, mean)
}
else if (profit < 0) {
apply(cbind(offerA, offerB, offerC), 1, min)
}
)
In this example the new df will be:
df
profit offerA offerB offerC bid
1 1 -0.51 0.91 6 6
2 1 -0.03 0.75 4 4
3 0 -1.02 0.28 5 1.42
4 0 0.63 0.61 1 0.75
5 0 2.32 0.37 2 1.56
6 -1 -0.15 0.43 3 -0.15
Because the value of bid is computed by rows, I want to write a function addBid() so that I can use something like apply(df, 1, addBid) but I can’t think of a good way adding my conditions above into the function. I hope I’m clear with my question. Thanks!
Maybe this could be useful
Where
xis your data.frame,refis the reference variable (profit) andaddis a logical indicating if you wantbidas a vector (ifadd=FALSE) or your original data.frame withbidas a new column (ifadd=TRUE).