I have a dataframe:
test <- data.frame(
ID = c(1001,1002,1003, 1004),
b_done = c('Y', 'Y', 'Y', 'Y'),
dd_complete = c(12, 19, 0, 8),
dd_payment = c(12,20,0,12)
)
I want to create a new column total_payment
based on the following conditions:
a) if b_done
== Y and dd_complete
> 0, total_payment
should be 5 dd_payment
b) if b_done
== Y and dd_complete
== 0, total_payment
should be 0
The output should be like this:
test <- data.frame(
ID = c(1001,1002,1003, 1004),
b_done = c('Y', 'Y', 'Y', 'Y'),
dd_complete = c(12, 19, 0, 8),
dd_payment = c(12,20,0,12),
total_payment = c(17, 25, 0, 17)
)
How may I do this? Thank you!
CodePudding user response:
We can use a condition in case_when
to create the column
library(dplyr)
test <- test %>%
mutate(total_payment = case_when(b_done == 'Y' & dd_complete > 0 ~
5 dd_payment,
b_done == "Y" & dd_complete == 0 ~ 0))
-output
test
ID b_done dd_complete dd_payment total_payment
1 1001 Y 12 12 17
2 1002 Y 19 20 25
3 1003 Y 0 0 0
4 1004 Y 8 12 17
Or without an ifelse or case_when
test$total_payment <- with(test, dd_payment (b_done == "Y" &
dd_complete > 0) * 5)