lundi 12 février 2018

if_else does not work the way I want it to

I have this dataframe here:

structure(list(period = c(1, 1, 1, 1, 1, 1), time = structure(c(-2209006260, 
-2209010160, -2209012620, -2209014540, -2209016580, -2209018140
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), strength = c("5v5", 
"5v5", "5v5", "5v5", "5v5", "5v5"), team = c("TOR", "TOR", "TOR", 
"MTL", "MTL", "MTL"), shooter = c(28, 36, 19, 67, 13, 15), shot_type = c("W", 
"W", "T", "W", "S", "W"), a1 = c(21, 24, 3, 76, 81, 22), a2 = c(3, 
NA, 42, NA, 13, NA), a3 = c(2, NA, NA, NA, NA, NA), a1_zone = c("nl", 
"of", "ol", "dsl", "or", "nc"), a2_zone = c("dsc", NA, "ofp", 
NA, "or", NA), a3_zone = c("dl", NA, NA, NA, NA, NA), scoring_chance = c(NA, 
NA, NA, "Y", NA, "Y"), shots_on_goal = c("Y", NA, NA, "Y", NA, 
NA), odd_man = c(NA_character_, NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_), goals = c(NA, NA, 
NA, "Y", NA, NA), rebound = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), rebound_sog = c(NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_), 
    rebound_goals = c(NA_character_, NA_character_, NA_character_, 
    NA_character_, NA_character_, NA_character_), home_score_state = c(0, 
    0, 0, 0, -1, -1), goalie = c(31, 31, 31, 45, 45, 45), game_id = c(20001, 
    20001, 20001, 20001, 20001, 20001), date = structure(c(1444176000, 
    1444176000, 1444176000, 1444176000, 1444176000, 1444176000
    ), class = c("POSIXct", "POSIXt"), tzone = "UTC"), home_team = c("TOR", 
    "TOR", "TOR", "TOR", "TOR", "TOR"), away_team = c("MTL", 
    "MTL", "MTL", "MTL", "MTL", "MTL")), .Names = c("period", 
"time", "strength", "team", "shooter", "shot_type", "a1", "a2", 
"a3", "a1_zone", "a2_zone", "a3_zone", "scoring_chance", "shots_on_goal", 
"odd_man", "goals", "rebound", "rebound_sog", "rebound_goals", 
"home_score_state", "goalie", "game_id", "date", "home_team", 
"away_team"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", 
"data.frame"))

What I want is to change the columns: scoring_chance, shots_on_goal, goals, rebound_sog, and rebound_goals using if_else so that if the column has NA value, it will turn into a 0 and if else, turn it into 1.

What I have is this:

pass %>% 
  mutate(scoring_chance = if_else(scoring_chance == "NA", "0", "1"),
         shots_on_goal = if_else(shots_on_goal == "NA", "0", "1"),
         goals = if_else(goals == "NA", "0", "1"),
         rebound_sog = if_else(rebound_sog == "NA", "0", "1"),
         rebound_goals = if_else(rebound_goals == "NA", "0", "1")
  ) 

This turns everything that is not NA into 1, but still retains the NA values...

Aucun commentaire:

Enregistrer un commentaire