vendredi 7 juillet 2017

R sapply/lapply with multiple ifelse statements

I'm trying to simplify the following multiple ifelse code using sapply or lapply (still can't distinguish them).

My goal is to allocate points based on placement like shown below.

df$Point <- ifelse(df$Placement_v2 <= 1, 10,
ifelse(df$Placement_v2 <= 10, 9, 
ifelse(df$Placement_v2 <= 25, 8,
ifelse(df$Placement_v2 <= 50, 7, 1) )))

This code works okay, but I want to make a dataframe and simply my code above using sapply or lapply (or anyother function).

I've tried this code but is not working as expected. Only the rows with placement 1 get 10 points and other rows end up with 1.

<2nd code>

df$Point <- sapply(df2$Placement, function(x) ifelse(df$Placement_v2 <= x, df2$Point[df2$Placement == x], 1 ) )

How can I solve this problem?

Aucun commentaire:

Enregistrer un commentaire