#Let us complete some basic operations using R.
1+2
## [1] 3
1-4
## [1] -3
sqrt(9)
## [1] 3
log(10)
## [1] 2.302585
log(2.72) #natural log (ln)
## [1] 1.000632
4/2
## [1] 2
log10(5)
## [1] 0.69897
log10(10)
## [1] 1
#Batting Average=(No. of Hits)/(No. of At Bats)
#What is the batting average of a player that bats 29 hits in 112 at bats?
BA= (29)/(112)
BA
## [1] 0.2589286
Batting_Avarage=round(BA,digits = 3)
Batting_Avarage
## [1] 0.259
#Question_2:What is the batting average of a player that bats 42 hits in 212 at bats?
#On Base Percentage
#OBP=(H+BB+HBP)/(At Bats+H+BB+HBP+SF)
#Let us compute the OBP for a player with the following general stats
#AB=515,H=172,BB=84,HBP=5,SF=6
OBP=(42)/(212)
OBP
## [1] 0.1981132
On_Base_Percentage=round(OBP,digits = 3)
On_Base_Percentage
## [1] 0.198
On_Base_Percentage=round(OBP,digits = 3)
On_Base_Percentage
## [1] 0.198
#Question_3:Compute the OBP for a player with the following general stats:
#AB=565,H=156,BB=65,HBP=3,SF=7
# Logical Operations
3 == 8
## [1] FALSE
## [1] FALSE
3 != 8
## [1] TRUE
## [1] TRUE
3 <= 8
## [1] TRUE
## [1] TRUE
3 > 4
## [1] FALSE
## [1] FALSE
# Combination of statements
2 < 3 | 1 == 5
## [1] TRUE
## [1] TRUE
# Vectors
pitches_by_innings <- c(12, 15, 10, 20, 10)
strikes_by_innings <- c(9, 12, 6, 14, 9)
# Define two vectors
runs_per_9innings <- c(3, 4, 2, 5, 6)
hits_per_9innings <- c(8, 7, 5, 9, 6)
# Question_5: Get the first element of hits_per_9innings
hits_per_9innings[1]
## [1] 8
# Question_6: Get the last element
hits_per_9innings[length(hits_per_9innings)]
## [1] 6
# Using Tables
game_day <- c("Saturday", "Saturday", "Sunday", "Monday", "Saturday", "Tuesday", "Sunday", "Friday", "Friday", "Monday")
table(game_day)
## game_day
## Friday Monday Saturday Sunday Tuesday
## 2 2 3 2 1
# Question_9: Most frequent answer in the survey
getMode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
getMode(game_day)
## [1] "Saturday"
# Question_7: Most frequent value in hits_per_9innings
getMode(hits_per_9innings)
## [1] 8
# R Notebook Code
# Load necessary libraries (if needed)
# No libraries required for this task
# Question 8: Summarize the survey
game_day <- c("Saturday", "Saturday", "Sunday", "Monday", "Saturday",
"Tuesday", "Sunday", "Friday", "Friday", "Monday")
# Use the table() command to summarize
survey_summary <- table(game_day)
survey_summary
## game_day
## Friday Monday Saturday Sunday Tuesday
## 2 2 3 2 1
# Question 9: Define the getMode function
getMode <- function(x) {
unique_values <- unique(x)
unique_values[which.max(tabulate(match(x, unique_values)))]
}
# Use the getMode function to find the most frequent answer
most_frequent_day <- getMode(game_day)
most_frequent_day
## [1] "Saturday"