dimanche 1 mars 2020

dplyr if_else Error: `true` must be length x (length of `condition`) or one, not 0 in r

I have a dataframe that looks something like this:

df <- data.frame('Home Team'=c("Omaha South", "Millard North", "Elkhorn","Elkhorn"),                      
                 'Winner'=c("Omaha South", "Millard North", "Elkhorn","Elkhorn"),
                 'Won By'=c(8,22,4,30),
                 'Away Class'=c("TRUE", "FALSE", "TRUE", "FALSE"))

I'm trying to create a new column/variable using conditional if_else from dplyr. This had worked for me in the past but for some reason it is now giving me an error. Below is the r code and error:

df$'Pre Score' <- 
        if_else(df$`Away Class`=="FALSE", 
        if_else(df$Home.Team==df$Winner, .8 + (df$`Won By`/100) -1, -1.2 - (df$`Won By`/100) -1), 
        if_else(df$Home.Team==df$Winner, .8 + (df$`Won By`/100), -1.2 - (df$`Won By`/100)))

Error: true must be length 4 (length of condition) or one, not 0

I've read through multiple SO discussions (example, example, example) related to this but haven't been able to translate it into a solution for my problem. It seem to have something to do with the "if true" portion of the code. Apparently it thinks this is a length of one whereas I want it to be a length of 4, or to work for all rows. Tried replacing if_else with case_when but wasn't able to succeed there either.

Aucun commentaire:

Enregistrer un commentaire