Home > Net >  Replacing value of 2 or more variables(column) with another variable condition in R
Replacing value of 2 or more variables(column) with another variable condition in R

Time:11-30

DataframeBasically, Im trying to give the team in the snitchCatcher variable 5 goals in their specific homeGoals/awayGoals variable. `

ifelse(Df$snitchCatcher == "home", 
       Df$homeGoals   5, 
       Df$awayGoals   5)

`

This is the code that i use, it does give correct calculation in the console, but yet it is defined at 1 list and not yet make any change inside of the dataframe variable. Is there any chance i can directly change/replace the value of the variable with above condition?

I am very new to R, i have think about subsetting data, create a data with only 1 team then combine later, etc,... however i do not know what to do, and I have already late on my assignment. I really need some help to at least solve the above issue so I can continue. Please help.

I will post a screencap of the dataframe

CodePudding user response:

Try this:

Df$homeGoals <-  ifelse(Df$snitchCatcher == "home", 
       Df$homeGoals   5, 
       Df$homeGoals )

Df$awayGoals <-  ifelse(Df$snitchCatcher != "home", 
       Df$awayGoals   5, 
       Df$awayGoals )

CodePudding user response:

tidyverse/dplyr approach:

library(dplyr)

df %>%
    mutate(homeGoals = if_else(snitchCatcher == "home", homeGoals 5, homeGoals 0)) %>%
    mutate(awayGoals = if_else(snitchCatcher == "away", awayGoals 5, awayGoals 0))
  • Related