R# Substraction
22-3-5-7
## [1] 7
# Division
5/2
## [1] 2.5
# Exponentiation
10^3
## [1] 1000
# Square root
sqrt(14)
## [1] 3.741657
# Logarithms
log(10)
## [1] 2.302585
#Question_1: Compute the log base 5 of 10 and the log of 10.
log(10,base = 5)
## [1] 1.430677
log(10,base = 2)
## [1] 3.321928
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
#Rounding to 3 decimal places
Batting_Average=round(BA,digits = 3)
#Show Batting_Average
Batting_Average
## [1] 0.259
#Question_2:What is the batting average of a player that bats 42 hits in 212 at bats?
#Creating a new batting average
BA2=(42)/(212)
#Rounding to 3 decimal places
Batting_Average2=round(BA2,digits = 3)
Batting_Average2
## [1] 0.198
#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=(172+84+5)/(515+172+84+5+6)
OBP
## [1] 0.3337596
#Rounding to 3 decimal places
On_Base_Percentage=round(OBP,digits = 3)
On_Base_Percentage
## [1] 0.334
#Question_3:Compute the OBP for a player with the following general stats:
#AB=565,H=156,BB=65,HBP=3,SF=7
OBP=(156+65+3)/(565+156+65+3+7)
#Rounding to 3 decimal places
OBP=round(OBP,digits = 3)
OBP
## [1] 0.281
Often you will want to test whether something is less than, greater than or equal to something.
#LOGICAL QUESTIONS. Returns True or FlasE
3 == 8# Does 3 equals 8?
## [1] FALSE
3 != 8# Is 3 different from 8?
## [1] TRUE
3 <= 8# Is 3 less than or equal to 8?
## [1] TRUE
3>4
## [1] FALSE
The logical operators are & for logical
AND, | for logical OR,
and ! for NOT. These are some
examples:
# Logical Disjunction (or)
FALSE | FALSE # False OR False
## [1] FALSE
# Logical Conjunction (and)
TRUE & FALSE #True AND False
## [1] FALSE
# Negation
! FALSE # Not False
## [1] TRUE
# Combination of statements
2 < 3 | 1 == 5 # 2<3 is True, 1==5 is False, True OR False is True
## [1] TRUE
In R, you create a variable and assign it a value using
<- as follows
Total_Bases <- 6 + 5
Total_Bases*3
## [1] 33
#RECREATIN
Total_Goals <- 2 + 5
Total_Goals*2
## [1] 14
To see the variables that are currently defined, use ls
(as in “list”)
#see the variables that are currently defined
ls()
## [1] "BA" "BA2" "Batting_Average"
## [4] "Batting_Average2" "OBP" "On_Base_Percentage"
## [7] "Total_Bases" "Total_Goals"
To delete a variable, use rm (as in “remove”)
#delete a variable
rm(Total_Bases)
Either <- or = can be used to assign a
value to a variable, but I prefer <- because is less
likely to be confused with the logical operator ==
#RECREATION OF PREVIOUS TOPICS
WWT <- 54
ls()
## [1] "BA" "BA2" "Batting_Average"
## [4] "Batting_Average2" "OBP" "On_Base_Percentage"
## [7] "Total_Goals" "WWT"
rm(WWT)
ls()
## [1] "BA" "BA2" "Batting_Average"
## [4] "Batting_Average2" "OBP" "On_Base_Percentage"
## [7] "Total_Goals"
The basic type of object in R is a vector, which is an
ordered list of values of the same type. You can create a vector using
the c() function (as in “concatenate”).
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_9innings <- c(6, 14, 4, 13, 1)
runs_per_9innings
## [1] 6 14 4 13 1
hits_per_9innings<- c(10, 17, 7, 20, 4)
hits_per_9innings
## [1] 10 17 7 20 4
There are also some functions that will create vectors with regular patterns, like repeated elements.
# replicate function
#five times 2 and 4 times 1
rep(2, 5)
## [1] 2 2 2 2 2
rep(1,4)
## [1] 1 1 1 1
# consecutive numbers
#From 1 to 5 and 2 to 10
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, 10, by=2)
## [1] 1 3 5 7 9
# sequence from 2 to 13 with a step of 3
seq(2,13,by=3)
## [1] 2 5 8 11
Many functions and operators like + or -
will work on all elements of the vector.
# 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 minimum value in vector
min(pitches_by_innings)
## [1] 10
# find average value in vector
mean(pitches_by_innings)
## [1] 13.4
#Recreation
# add vectors
runs_per_9innings+hits_per_9innings
## [1] 16 31 11 33 5
# compare vectors
runs_per_9innings == hits_per_9innings
## [1] FALSE FALSE FALSE FALSE FALSE
# find length of vector
length(runs_per_9innings)
## [1] 5
# find minimum value in vector
min(runs_per_9innings)
## [1] 1
# find average value in vector
mean(runs_per_9innings)
## [1] 7.6
You can access parts of a vector by using [. Recall what
the value is of the vector pitches_by_innings.
pitches_by_innings
## [1] 12 15 10 20 10
# If you want to get the first element:
pitches_by_innings[1]
## [1] 12
#Recreation
runs_per_9innings
## [1] 6 14 4 13 1
# If you want to get the first element:
runs_per_9innings[3]
## [1] 4
#Question_5: Get the first element of hits_per_9innings.
#Recreation
hits_per_9innings
## [1] 10 17 7 20 4
# If you want to get the first element:
hits_per_9innings[1]
## [1] 10
If you want to get the last element of
pitches_by_innings without explicitly typing the number of
elements of pitches_by_innings, make use of the
length function, which calculates the length of a
vector:
pitches_by_innings[length(pitches_by_innings)]
## [1] 10
#Question_6: Get the last element of hits_per_9innings.
hits_per_9innings[length(hits_per_9innings)]
## [1] 4
hits_per_9innings[4]
## [1] 20
You can also extract multiple values from a vector. For instance to get the 2nd through 4th values use
pitches_by_innings[c(2, 3, 4)]
## [1] 15 10 20
Vectors can also be strings or logical values
player_positions <- c("catcher", "pitcher", "infielders", "outfielders")
In statistical applications, data is often stored as a data frame, which is like a spreadsheet, with rows as observations and columns as variables.
To manually create a data frame, use the data.frame()
function.
# Creating a data frame with three columns: bonus, active_roster, and salary
# Column 'bonus' with values 2, 3, and 1 (in millions)
bonus <- c(2, 3, 1)
# Column 'active_roster' with values "yes", "no", and "yes"
active_roster <- c("yes", "no", "yes")
# Column 'salary' with values 1.5, 2.5, and 1 (in millions)
salary <- c(1.5, 2.5, 1)
# Creating the data frame using the above columns
df <- data.frame(bonus = bonus, active_roster = active_roster, salary = salary)
Most often you will be using data frames loaded from a file. For
example, load the results of a fan’s survey. The function
load or read.table can be used for this.
To randomly select a sample use the function sample().
The following code selects 5 numbers between 1 and 10 at random (without
duplication)
# Generating a random sample of size 5 from the numbers 1 to 10 (inclusive)
sample(1:10, size = 5)
## [1] 1 7 6 10 2
size=) gives the size of the
sample to select.Taking a simple random sample from a data frame is only slightly more complicated, having two steps:
sample() to select a sample of size n
from a vector of the row numbers of the data frame.[ to select those rows from the
data frame.Consider the following example with fake data. First, make
up a data frame with two columns. (LETTERS is a character
vector of length 26 with capital letters âAâ to âZâ;
LETTERS is automatically defined and pre-loaded in
R)
# Creating a data frame 'bar' with two columns: var1 and var2
# Column 'var1' with letters A to J
var1 <- LETTERS[1:10]
# Column 'var2' with values 1 to 10
var2 <- 1:10
# Creating the data frame using the above columns
bar <- data.frame(var1 = var1, var2 = var2)
# Checking the contents of the data frame 'bar'
bar
Suppose you want to select a random sample of size 5. First, define a
variable n with the size of the sample, i.e. 5
n <- 5
Now, select a sample of size 5 from the vector with 1 to 10 (the
number of rows in bar). Use the function
nrow() to find the number of rows in bar
instead of manually entering that number.
Use : to create a vector with all the integers between 1
and the number of rows in bar.
# Generating a random sample of row indices from the data frame 'bar'
# Creating 'samplerows' by sampling 'n' row indices from 1 to the number of rows in 'bar'
samplerows <- sample(1:nrow(bar), size = n)
# Printing the sampled row indices
samplerows
## [1] 4 10 3 5 8
The variable samplerows contains the rows of
bar which make a random sample from all the rows in
bar. Extract those rows from bar with
# Extracting rows from the data frame 'bar' based on the sampled row indices
# Creating a new data frame 'barsample' by selecting rows using the sampled row indices
barsample <- bar[samplerows, ]
# Printing the resulting sample data frame
print(barsample)
## var1 var2
## 4 D 4
## 10 J 10
## 3 C 3
## 5 E 5
## 8 H 8
The code above creates a new data frame called
barsample with a random sample of rows from
bar.
In a single line of code:
# Creating a random sample of 'n' rows from the data frame 'bar' directly
# Using the sample function to randomly select 'n' row indices from 1 to the number of rows in 'bar'
# Then, extracting the corresponding rows from 'bar'
bar[sample(1:nrow(bar), n), ]
The table() command allows us to look at tables. Its
simplest usage looks like table(x) where x is
a categorical variable.
For example, a survey asks people if they support the home team or not. The data is
Yes, No, No, Yes, Yes
We can enter this into R with the c() command, and
summarize with the table() command as follows
# Creating a vector 'x' with categorical values "Yes" and "No"
x <- c("Yes", "No", "No", "Yes", "Yes")
# Generating a frequency table for the values in vector 'x'
table(x)
## x
## No Yes
## 2 3
Suppose, MLB Teams’ CEOs yearly compensations are sampled and the following are found (in millions)
12 .4 5 2 50 8 3 1 4 0.25
# Creating a numeric vector 'sals' with salary values
sals <- c(12, 0.4, 5, 2, 50, 8, 3, 1, 4, 0.25)
# Calculating various summary statistics for the 'sals' vector
# Calculating the mean (average) of the salaries
mean(sals)
## [1] 8.565
# Calculating the variance of the salaries
var(sals)
## [1] 225.5145
# Calculating the standard deviation of the salaries
sd(sals)
## [1] 15.01714
# Calculating the median of the salaries
median(sals)
## [1] 3.5
# Calculating Tukey's five-number summary for boxplots
# The five numbers represent: min, lower hinge, median, upper hinge, max
fivenum(sals)
## [1] 0.25 1.00 3.50 8.00 50.00
# Displaying a summary of basic statistics for the 'sals' vector
summary(sals)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.250 1.250 3.500 8.565 7.250 50.000
In R we can write our own functions, and a first example of
a function is shown below in order to compute the mode of a
vector of observations x
# Function to find the mode (most frequent value) in a vector
getMode <- function(x) {
# Extracting unique values from the input vector
ux <- unique(x)
# Finding the index of the maximum frequency using tabulate and match functions
mode_index <- which.max(tabulate(match(x, ux)))
# Returning the mode value
ux[mode_index]
}
As an example, we can use the function defined above to find the most
frequent value of the number of pitches_by_innings
# Most frequent value in pitches_by_innings
getMode(pitches_by_innings)
## [1] 10
#Question_7: Find the most frequent value of hits_per_9innings.
getMode(hits_per_9innings)
## [1] 10
#Question_8: Summarize the following survey with the `table()` command:
#What is your favorite day of the week to watch baseball? A total of 10 fans submitted this survey.
#Saturday, Saturday, Sunday, Monday, Saturday,Tuesday, Sunday, Friday, Friday, Monday
# Creating a vector 'game_day' with survey responses
game_day <- c("Saturday", "Saturday", "Sunday", "Monday", "Saturday", "Tuesday", "Sunday", "Friday", "Friday", "Monday")
# Using the table() command to summarize the survey responses
table(game_day)
## game_day
## Friday Monday Saturday Sunday Tuesday
## 2 2 3 2 1
game_day
## [1] "Saturday" "Saturday" "Sunday" "Monday" "Saturday" "Tuesday"
## [7] "Sunday" "Friday" "Friday" "Monday"
table(game_day)
## game_day
## Friday Monday Saturday Sunday Tuesday
## 2 2 3 2 1
#Question_9: What is the most frequent answer recorded in the survey? Use the getMode function to compute results.
# Function to find the mode (most frequent value) in a vector
getMode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
# Applying the getMode function to the 'game_day' vector
most_frequent_answer <- getMode(game_day)
# Printing the most frequent answer
print(most_frequent_answer)
## [1] "Saturday"
getMode(game_day)
## [1] "Saturday"