#This is my code
Purchase = function(credit_data)
{
if(credit_data$ONEOFF_PURCHASES == 0 & credit_data$INSTALLMENTS_PURCHASES == 0)
return = "none"
if(credit_data$ONEOFF_PURCHASES > 0 & credit_data$INSTALLMENTS_PURCHASES > 0)
return = "both_oneoff_installment"
if(credit_data$ONEOFF_PURCHASES > 0 & credit_data$INSTALLMENTS_PURCHASES == 0)
return = "one_off"
if(credit_data$ONEOFF_PURCHASES == 0 & credit_data$INSTALLMENTS_PURCHASES > 0)
return = "installment"
}
*** I have a data set in which iam trying to create a new variable with the help of combination of variables in the dataset as mentioned in the function above ***
Iam trying to call the function as
credit_data$Purchase_Type = apply(Purchase(credit_data))
** This code is not working can you suggest me a better code line to create a new variable which will have the above mentioned values whenever the combination matches**
** Please help**
You should consider to use or learn dplyr
.
You can see dplyr with this link
Also return
statement should be changed.
I think this code isn't looks elegant, but still you can use.
library(dplyr)
# example data
credit_data = data.frame(
O = c(0,0,1,1),
I = c(0,1,0,1)
)
# I changed variables as C, O, I it's too long.
Purchase = function(C){
sapply(1:nrow(C), function(i){
if(!C$O[i] && !C$I[i] ) return ("none")
if(C$O[i] && C$I[i] ) return ("one_off")
if(!C$O[i] && C$I[i]) return ("installment")
if(C$O[i] && C$I[i]) return ("both_oneoff_installment")
})
}
credit_data %>%
mutate(Purchase_Type = Purchase(credit_data))
Regards.
1 Like
The tests in line 2 and 4 in your if-sequence are identical.
O I Purchase_Type
1 0 0 none
2 0 1 installment
3 1 0 NULL
4 1 1 one_off
Apart from that good suggestions
line2 should be if(C$O[i] && !C$I[i] ) return ("one_off")
.
my mistake
Thank you very much for helping out, your code worked out.
@jhk0530
I can only mention one of you anyhow thank you
system
Closed
April 5, 2020, 7:54am
6
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.