# Addition
2+3
[1] 5
# Division
2/3
[1] 0.6666667
# Exponentiation
2^3
[1] 8
# Square root
sqrt(2)
[1] 1.414214
# Logarithms
log(2)
[1] 0.6931472
Question 1: Compute the log base 5 of 10 and the log of 10
log10(5)
[1] 0.69897
log(10)
[1] 2.302585
Computing some offensive metrics in Baseball
#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_Average=round(BA,digits = 3)
Batting_Average
[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+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=(172+84+5)/(515+84+5+6)
OBP
[1] 0.4278689
On_Base_Percentage=round(OBP,digits = 3)
On_Base_Percentage
[1] 0.428
Often you will want to test whether something is less than, greater than or equal to something.
#Question_3:Compute the OBP for a player with the following general stats:
#AB=565,H=156,BB=65,HBP=3,SF=7
#OBP=(H+BB+HBP)/(AT Bats+BB=HBP+SF)
OBP = (156+65+3)/(565+65+3+7)
On_Base_Percentage=round(OBP,digits = 3)
On_Base_Percentage
[1] 0.35
# Combination of statements
2 < 3 | 1 == 5 # 2<3 is True, 1==5 is False, True OR False is True
[1] TRUE
Total_Bases <- 6 + 5
Total_Bases*3
[1] 33
ls()
[1] "BA" "Batting_Average" "OBP"
[4] "On_Base_Percentage" "Total_Bases"
rm(Total_Bases)
Vector
pitches_by_innings <- c(12, 15, 10, 20, 10)
pitches_by_innings
[1] 12 15 10 20 10
strikes_by_innings <- c(9, 12, 6, 14, 9)
strikes_by_innings
[1] 9 12 6 14 9
#Question_4: Define two vectors,runs_per_9innings and hits_per_9innings, each with five elements.
runs_per_9inning<-c(2,5,7,11,13)
hits_per_9innings<-c(11,13,16,18,19)
runs_per_9inning
[1] 2 5 7 11 13
hits_per_9innings
[1] 11 13 16 18 19
# replicate function
rep(2, 5)
[1] 2 2 2 2 2
# consecutive numbers
1:5
[1] 1 2 3 4 5
2:10
[1] 2 3 4 5 6 7 8 9 10
# sequence from 1 to 10 with a step of 2
seq(1, 20, by=3)
[1] 1 4 7 10 13 16 19
# add vectors
pitches_by_innings+strikes_by_innings
[1] 21 27 16 34 19
# compare vectors
pitches_by_innings == strikes_by_innings
[1] FALSE FALSE FALSE FALSE FALSE
# find length of vector
length(pitches_by_innings)
[1] 5
# find average value in vector
mean(pitches_by_innings)
[1] 13.4
pitches_by_innings
[1] 12 15 10 20 10
# If you want to get the first element:
pitches_by_innings[1]
[1] 12
#Question_5: Get the first element of hits_per_9innings.
pitches_by_innings[length(pitches_by_innings)]
[1] 10
#Question_6: Get the last element of hits_per_9innings.
pitches_by_innings[c(2, 3, 4)]
[1] 15 10 20
player_positions <- c("catcher", "pitcher", "infielders", "outfielders")
data.frame(bonus = c(2, 3, 1),#in millions
active_roster = c("yes", "no", "yes"),
salary = c(1.5, 2.5, 1))#in millions
sample(1:10, size=5)
[1] 5 4 7 6 1
bar <- data.frame(var1 = LETTERS[1:10], var2 = 1:10)
# Check data frame
bar
n <- 5