Chapter 10 If block
When creating a new column we may want the values of the column to be different depending on some condition. We can do this with an if block.
## We will be creating a player type variabe that shows they are "bad" if batting average < 0.25, good if below 0.75 and great if greater than or equal to 0.75
# Create for loop to look at each player separatly
for(i in 1:nrow(hits_data_frame)){
## isolate player
player_average <- hits_data_frame$batting_average[i]
## bad condition
if(player_average < 0.25){
## Assign new bad value to new variable
hits_data_frame$player_type[i] <- "bad"
}
## Assign new good value to new variable
if(player_average >= 0.25 & player_average<0.75){
hits_data_frame$player_type[i] <- "good"
}
## Assign great value to new value
if(player_average>=0.75){
hits_data_frame$player_type[i] <- "great"
}
}
hits_data_frame
## PlayerID Hits AtBats batting_average outs player_type
## 1 Player01 3 4 0.75 1 great
## 2 Player02 1 4 0.25 3 good
## 3 Player03 0 3 0.00 3 bad
## 4 PlayerNew 2 5 0.40 3 good
## 5 Player05 4 4 1.00 0 great
you can use the table function to see how many of each type of player you have.
##
## bad good great
## 1 2 2
10.0.1 Challenge
Create a “team” variable with a while loop or for loop to look at each players “player_type”. If they “player_type” is great, then assign them to the “Cardinals”. If the player type is good, then send them to the “Twins”. If a “player_type” is bad then assign them to the “Dodgers”