Mans.hu

Of life and all its colors

About everything that amazes and confounds me.

About / Blog / Contact
  • 
  • 
  • 
  • 

Categories

  • Amazing
  • Books
  • Business and Technology
  • Chess
  • History
  • Mahabharata
  • Parenting

Search

How to write a Nested Ifelse in R?

April 17, 2019 by manshu Leave a Comment

With the database of all my classical games created – I wanted to add two columns to the data frame to indicate what color I was in the game, and the result. Here is the data frame in a CSV format so you can understand the structure.

In order to determine whether I was black or white – I can simply evaluate if my username was present in the White or Black variable, and assign a color based on that.

This is the code that does that:

a <- ifelse(tal$White == “manshuv”, “White”, “Black”)

I first tried writing an If statement but R doesn’t evaluate an If statement on the entire vector rather it does so only on the first record. In order to run the statement on the entire vector you need to use the Ifelse statement, and that is the statement above.

The next thing I wanted to do was to record my wins and losses, and for that you need a slightly more involved Ifelse statement in the form of a nested statement.

This is the code for that:

Result_1 <- ifelse (tal$Result == “1/2-1/2”, “Draw”,
+ (ifelse(tal$White == “manshuv” &tal$Result == “1-0”, “Won”,
+ (ifelse(tal$Black == “manshuv” & tal$Result == “0-1”, “Won”, “Lost”)))))

In the first line of the code above – R evaluates if the result was 1/2-1/2, and if so it assigns Draw as the result.

The second check is to see if the color was White and the result was 1-0 as that is a win, and if that fails then check if the color was black and the result was 0-1 and that is a win for me. All other outcomes are my losses.

You can then add these two columns to the data frame by using the mutate command as follows:

tal <- mutate(tal, Result_1)

Filed Under: Business and Technology

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *