Total Winnings Calculation in R
Total Winnings Calculation in R
Now that you have the poker and roulette winnings nicely as named vectors, you can
start doing some data analytical magic.
• How much has been your overall profit or loss per day of the week?
• Have you lost money over the week in total?
• Are you winning/losing money on poker or on roulette?
It is important to know that if you sum two vectors in R, it takes the element-wise
sum. For example, the following three statements are completely equivalent:
c(1, 2, 3) + c(4, 5, 6)
c(1 + 4, 2 + 5, 3 + 6)
c(5, 7, 9)
You can also do the calculations with variables that represent vectors:
a <- c(1, 2, 3)
b <- c(4, 5, 6)
c <- a + b
A_vector <- c(1, 2, 3)
B_vector <- c(4, 5, 6)
A function that helps you to answer this question is sum(). It calculates the sum of all
elements of a vector. For example, to calculate the total amount of money you have
lost/won with poker you do:
After a short brainstorm in your hotel's jacuzzi, you realize that a possible
explanation might be that your skills in roulette are not as well developed as your
skills in poker. So maybe your total gains in poker are higher (or > ) than in roulette.
Another possible route for investigation is your performance at the beginning of the
working week compared to the end of it. You did have a couple of Margarita cocktails
at the end of the week…
To answer that question, you only want to focus on a selection of the total_vector.
In other words, our goal is to select specific elements of the vector. To select
elements of a vector (and later matrices, data frames, …), you can use square
brackets. Between the square brackets, you indicate what elements to select. For
example, to select the first element of the vector, you type poker_vector[1]. To
select the second element of the vector, you type poker_vector[2], etc. Notice that
the first element in a vector has index 1, not 0 as in many other programming
languages.
To select multiple elements from a vector, you can add square brackets at the end of
it. You can indicate between the brackets what elements should be selected. For
example: suppose you want to select the first and the fifth day of the week: use the
vector c(1, 5) between the square brackets. For example, the code below selects
the first and fifth element of poker_vector:
poker_vector[c(1, 5)]
# Poker and roulette winnings from Monday to Friday:
poker_vector <- c(140, -50, 20, -120, 240)
roulette_vector <- c(-24, -50, 100, -350, 10)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday")
names(poker_vector) <- days_vector
names(roulette_vector) <- days_vector
So, another way to find the mid-week results is poker_vector[2:4]. Notice how the
vector 2:4 is placed between the square brackets to select element 2 up to 4.
poker_vector["Monday"]
will select the first element of poker_vector since "Monday" is the name of that first
element.
Just like you did in the previous exercise with numerics, you can also use the
element names to select multiple elements, for example:
poker_vector[c("Monday","Tuesday")]
# Poker and roulette winnings from Monday to Friday:
poker_vector <- c(140, -50, 20, -120, 240)
roulette_vector <- c(-24, -50, 100, -350, 10)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday")
names(poker_vector) <- days_vector
names(roulette_vector) <- days_vector
As seen in the previous chapter, stating 6 > 5 returns TRUE. The nice thing about R is
that you can use these comparison operators also on vectors. For example:
c(4, 5, 6) > 5
[1] FALSE FALSE TRUE
This command tests for every element of the vector if the condition stated by the
comparison operator is TRUE or FALSE.
In the previous exercises you used selection_vector <- poker_vector > 0 to find
the days on which you had a positive poker return. Now, you would like to know not
only the days on which you won, but also how much you won on those days.
You can select the desired elements, by putting selection_vector between the
square brackets that follow poker_vector:
poker_vector[selection_vector]
R knows what to do when you pass a logical vector in square brackets: it will only
select the elements that correspond to TRUE in selection_vector.
# Poker and roulette winnings from Monday to Friday:
poker_vector <- c(140, -50, 20, -120, 240)
roulette_vector <- c(-24, -50, 100, -350, 10)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday")
names(poker_vector) <- days_vector
names(roulette_vector) <- days_vector
What's a matrix?
In R, a matrix is a collection of elements of the same data type (numeric, character,
or logical) arranged into a fixed number of rows and columns. Since you are only
working with rows and columns, a matrix is called two-dimensional.
You can construct a matrix in R with the matrix() function. Consider the following
example:
In the editor, three vectors are defined. Each one represents the box office numbers
from the first three Star Wars movies. The first element of each vector indicates the
US box office revenue, the second element refers to the Non-US box office (source:
Wikipedia).
In this exercise, you'll combine all these figures into a single vector. Next, you'll build
a matrix from this vector.
# Create box_office
box_office <- c(new_hope,empire_strikes,return_jedi)
# Construct star_wars_matrix
star_wars_matrix <-matrix(box_office,byrow=TRUE,nrow=3)
star_wars_matrix
Naming a matrix
To help you remember what is stored in star_wars_matrix, you would like to add the
names of the movies for the rows. Not only does this help you to read the data, but it
is also useful to select certain elements from the matrix.
Similar to vectors, you can add names for the rows and the columns of a matrix
We went ahead and prepared two vectors for you: region, and titles. You will need
these vectors to name the columns and rows of star_wars_matrix, respectively.
# Box office Star Wars (in millions!)
new_hope <- c(460.998, 314.4)
empire_strikes <- c(290.475, 247.900)
return_jedi <- c(309.306, 165.8)
# Construct matrix
star_wars_matrix <- matrix(c(new_hope, empire_strikes, return_
jedi), nrow = 3, byrow = TRUE)
To calculate the total box office revenue for the three Star Wars movies, you have to
take the sum of the US revenue column and the non-US revenue column.
In R, the function rowSums() conveniently calculates the totals for each row of a
matrix. This function creates a new vector:
rowSums(my_matrix)
# Construct star_wars_matrix
box_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165
.8)
region <- c("US", "non-US")
titles <- c("A New Hope",
"The Empire Strikes Back",
"Return of the Jedi")
You can add a column or multiple columns to a matrix with the cbind() function,
which merges matrices and/or vectors together by column. For example:
Adding a row
Just like every action has a reaction, every cbind() has an rbind(). (We admit, we
are pretty bad with metaphors.)
Your R workspace, where all variables you defined 'live' (check out what a
workspace is), has already been initialized and contains two matrices:
• star_wars_matrix that we have used all along, with data on the original
trilogy,
• star_wars_matrix2, with similar data for the prequels trilogy.
Explore these matrices in the console if you want to have a closer look. If you want
to check out the contents of the workspace, you can type ls() in the console.
• my_matrix[1,2] selects the element at the first row and second column.
• my_matrix[1:3,2:4] results in a matrix with the data on the rows 1, 2, 3 and
columns 2, 3, 4.
If you want to select all elements of a row or a column, no number is needed before
or after the comma, respectively:
Back to Star Wars with this newly acquired knowledge! As in the previous
exercise, all_wars_matrix is already available in your workspace.
As a newly-hired data analyst for Lucasfilm, it is your job to find out how many
visitors went to each movie for each geographical area. You already have the total
revenue figures in all_wars_matrix. Assume that the price of a ticket was 5 dollars.
Simply dividing the box office numbers by this ticket price gives you the number of
visitors.
After looking at the result of the previous exercise, big boss Lucas points out that the
ticket prices went up over time. He asks to redo the analysis based on the prices you
can find in ticket_prices_matrix (source: imagination).
Those who are familiar with matrices should note that this is not the standard matrix
multiplication for which you should use %*% in R.
# US visitors
us_visitors <- visitors[,1]
us_visitors
A New Hope The Empire Strikes Back Return of the Jedi
92.20000 48.41667 44.18571
The Phantom Menace Attack of the Clones Revenge of the Sith
118.62500 69.04444 77.61224
Scores Comments
5 Amazing!
4.8 I liked it
It would be useful to collect together all the pieces of information about the movie, like the
title, actors, and reviews into a single variable. Since these pieces of data are different shapes,
it is natural to combine them in a list variable.
movie_title, containing the title of the movie, and movie_actors, containing the names of
some of the actors in the movie, are available in your workspace.
Instructions
0 XP
Instructions
0 XP
• Create two vectors, called scores and comments, that contain the information from the
reviews shown in the table.
• Find the average of the scores vector and save it as avg_review.
• Combine the scores and comments vectors into a data frame called reviews_df.
• Create a list, called departed_list, that contains the movie_title, movie_actors,
reviews data frame as reviews_df, and the average review score as avg_review, and
print it out.
•
• # Use the table from the exercise to define the comments
and scores vectors
• scores <- c(4.6, 5, 4.8, 5, 4.2)
• comments <- c("I would watch it again", "Amazing!", "I li
ked it", "One of the best movies", "Fascinating plot")
•
• # Save the average of the scores vector as avg_review
• avg_review <- mean(scores)
•
• # Combine scores and comments into the reviews_df data fr
ame
• reviews_df <- [Link](scores, comments)
•
• # Create and print out a list, called departed_list
• departed_list <- list(movie_title, movie_actors, reviews_
df, avg_review)
• departed_list
It is clear that there are two categories, or in R-terms 'factor levels', at work here:
"Male" and "Female".
A nominal variable is a categorical variable without an implied order. This means that
it is impossible to say that 'one is worth more than the other'. For example, think of
the categorical variable animals_vector with the
categories "Elephant", "Giraffe", "Donkey" and "Horse". Here, it is impossible to
say that one stands above or below the other. (Note that some of you might disagree
;-) ).
In contrast, ordinal variables do have a natural ordering. Consider for example the
categorical variable temperature_vector with the
categories: "Low", "Medium" and "High". Here it is obvious that "Medium" stands
above "Low", and "High" stands above "Medium".
# Animals
animals_vector <- c("Elephant", "Giraffe", "Donkey", "Horse")
factor_animals_vector <- factor(animals_vector)
factor_animals_vector
# Temperature
temperature_vector <- c("High", "Low", "High","Low", "Medium")
factor_temperature_vector <- factor(temperature_vector, order
= TRUE, levels = c("Low", "Medium", "High"))
factor_temperature_vector
Factor levels
When you first get a dataset, you will often notice that it contains factors with specific
factor levels. However, sometimes you will want to change the names of these levels
for clarity or other reasons. R allows you to do this with the function levels():
A good illustration is the raw data that is provided to you by a survey. A common
question for every questionnaire is the sex of the respondent. Here, for simplicity,
just two categories were recorded, "M" and "F". (You usually need more categories
for survey data; either way, you use a factor to store the categorical data.)
Recording the sex with the abbreviations "M" and "F" can be convenient if you are
collecting data with pen and paper, but it can introduce confusion when analyzing the
data. At that point, you will often want to change the factor levels
to "Male" and "Female" instead of "M" and "F" for clarity.
Watch out: the order with which you assign the levels is important. If you
type levels(factor_survey_vector), you'll see that it outputs [1] "F" "M". If you
don't specify the levels of the factor when creating the vector, R will automatically
assign them alphabetically. To correctly map "F" to "Female" and "M" to "Male", the
levels should be set to c("Female", "Male"), in this order.
factor_survey_vector
Summarizing a factor
After finishing this course, one of your favorite functions in R will be summary(). This
will give you a quick overview of the contents of a variable:
summary(my_var)
Going back to our survey, you would like to know how many "Male" responses you
have in your study, and how many "Female" responses. The summary() function
gives you the answer to this question.
# Male
male <- factor_survey_vector[1]
# Female
female <- factor_survey_vector[2]
Ordered factors
Since "Male" and "Female" are unordered (or nominal) factor levels, R returns a
warning message, telling you that the greater than operator is not meaningful. As
seen before, R attaches an equal value to the levels for such factors.
But this is not always the case! Sometimes you will also deal with factors that do
have a natural ordering between its categories. If this is the case, we have to make
sure that we pass this information to R…
Let us say that you are leading a research team of five data analysts and that you
want to evaluate their performance. To do this, you track their speed, evaluate each
analyst as "slow", "medium" or "fast", and save the results in speed_vector.
# Create speed_vector
speed_vector <-c("medium","slow","slow","medium","fast")
factor(some_vector,
ordered = TRUE,
levels = c("lev1", "lev2" ...))
By setting the argument ordered to TRUE in the function factor(), you indicate that
the factor is ordered. With the argument levels you give the values of the factor in
the correct order.
# Create speed_vector
speed_vector <- c("medium", "slow", "slow", "medium", "fast")
# Print factor_speed_vector
factor_speed_vector
summary(factor_speed_vector)
# Create factor_speed_vector
speed_vector <- c("medium", "slow", "slow", "medium", "fast")
factor_speed_vector <- factor(speed_vector, ordered = TRUE, le
vels = c("slow", "medium", "fast"))
When doing a market research survey, however, you often have questions such as:
• 'Are you married?' or 'yes/no' questions (logical)
• 'How old are you?' (numeric)
• 'What is your opinion on this product?' or other 'open-ended' questions
(character)
• …
The output, namely the respondents' answers to the questions formulated above, is
a dataset of different data types. You will often find yourself working with datasets
that contain different data types instead of only one.
A data frame has the variables of a dataset as columns and the observations as
rows. This will be a familiar concept for those coming from different statistical
software packages such as SAS or SPSS.
Working with large datasets is not uncommon in data analysis. When you work with
(extremely) large datasets and data frames, your first task as a data analyst is to
develop a clear understanding of its structure and main elements. Therefore, it is
often useful to show only a small part of the entire dataset.
So how to do this in R? Well, the function head() enables you to show the first
observations of a data frame. Similarly, the function tail() prints out the last
observations in your dataset.
Both head() and tail() print a top line called the 'header', which contains the names
of the different variables in your dataset.
Applying the str() function will often be the first thing that you do when receiving a
new dataset or data frame. It is a great way to get more insight in your dataset
before diving into the real analysis.
# Investigate the structure of mtcars
str(mtcars)
As a first goal, you want to construct a data frame that describes the main
characteristics of eight planets in our solar system. According to your good friend
Buzz, the main features of a planet are:
After doing some high-quality research on Wikipedia, you feel confident enough to
create the necessary vectors: name, type, diameter, rotation and rings; these
vectors have already been coded up in the editor. The first element in each of these
vectors correspond to the first observation.
You construct a data frame with the [Link]() function. As arguments, you pass
the vectors from before: they will become the different columns of your data frame.
Because every column has the same length, the vectors you pass should also have
the same length. But don't forget that it is possible (and likely) that they contain
different types of data.
# Definition of vectors
name <- c("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune")
type <- c("Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet", "Gas giant",
"Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532,
11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03,
0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
• my_df[1,2] selects the value at the first row and second column in my_df.
• my_df[1:3,2:4] selects rows 1, 2, 3 and columns 2, 3, 4 in my_df.
Suppose you want to select the first three elements of the type column. One way to
do this is
planets_df[1:3,2]
A possible disadvantage of this approach is that you have to know (or look up) the
column number of type, which gets hard if you have a lot of variables. It is often
easier to just make use of the variable name:
planets_df[1:3,"type"]
# The planets_df data frame from the previous exercise is pre-
loaded
# Select first 5 values of diameter column
planets_df[1:5,"diameter"]
planets_df[,3]
planets_df[,"diameter"]
However, there is a short-cut. If your columns have names, you can use the $ sign:
planets_df$diameter
# planets_df is pre-loaded in your workspace
This means that the first four observations (or planets) do not have a ring (FALSE),
but the other four do (TRUE). However, you do not get a nice overview of the names
of these planets, their diameter, etc. Let's try to use rings_vector to select the data
for the four planets with rings.
# Adapt the code to select all columns for planets with rings
planets_df[rings_vector, "name"]
# planets_df and rings_vector are pre-loaded in your workspace
# Adapt the code to select all columns for planets with rings
planets_df[rings_vector,]
Only planets with rings but shorter
So what exactly did you learn in the previous exercises? You selected a subset from
a data frame (planets_df) based on whether or not a certain condition was true
(rings or no rings), and you managed to pull out all relevant data. Pretty awesome!
By now, NASA is probably already flirting with your CV ;-).
Now, let us move up one level and use the function subset(). You should see
the subset() function as a short-cut to do exactly the same as what you did in the
previous exercises.
The first argument of subset() specifies the dataset for which you want a subset. By
adding the second argument, you give R the necessary information and conditions to
select the correct subset.
The code below will give the exact same result as you got in the previous exercise,
but this time, you didn't need the rings_vector!
Sorting
Making and creating rankings is one of mankind's favorite affairs. These rankings
can be useful (best universities in the world), entertaining (most influential movie
stars) or pointless (best 007 look-a-like).
In data analysis you can sort your data according to a certain variable in the dataset.
In R, this is done with the help of the function order().
order() is a function that gives you the ranked position of each element when it is
applied on a variable, such as a vector for example:
10, which is the second element in a, is the smallest element, so 2 comes first in the
output of order(a). 100, which is the first element in a is the second smallest
element, so 1 comes second in the output of order(a).
a[order(a)]
[1] 10 100 1000
A list in R allows you to gather a variety of objects under one name (that is, the name
of the list) in an ordered way. These objects can be matrices, vectors, data frames,
even other lists, etc. It is not even required that these objects are related to each
other in any way.
You could say that a list is some kind super data type: you can store practically any
piece of information in it!
Creating a list
Let us create our first list! To construct a list you use the function list():
my_list <- list(comp1, comp2 ...)
The arguments to the list function are the list components. Remember, these
components can be matrices, vectors, other lists, …
Just like on your to-do list, you want to avoid not knowing or remembering what the
components of your list stand for. That is why you should give names to them:
This creates a list with components that are named name1, name2, and so on. If you
want to name your lists after you've created them, you can use the names() function
as you did with vectors. The following commands are fully equivalent to the
assignment above:
Start by creating a list for the movie "The Shining". We have already created the
variables mov, act and rev in your R workspace. Feel free to check them out in the
console.
One way to select a component is using the numbered position of that component.
For example, to "grab" the first component of shining_list you type
shining_list[[1]]
A quick way to check this out is typing it in the console. Important to remember: to
select elements from vectors, you use single square brackets: [ ]. Don't mix them
up!
You can also refer to the names of the components, with [[ ]] or with the $ sign.
Both will select the data frame representing the reviews:
shining_list[["reviews"]]
shining_list$reviews
Besides selecting components, you often need to select specific elements out of
these components. For example, with shining_list[[2]][1] you select from the
second component, actors (shining_list[[2]]), the first element ([1]). When you
type this in the console, you will see the answer is Jack Nicholson.
# shining_list is already pre-loaded in the workspace
Scores Comments
5 Amazing!
4.8 I liked it
It would be useful to collect together all the pieces of information about the movie,
like the title, actors, and reviews into a single variable. Since these pieces of data are
different shapes, it is natural to combine them in a list variable.
# Use the table from the exercise to define the comments and s
cores vectors
scores <- c(4.6, 5, 4.8, 5,4.2)
comments <- c("I would watch it again", "Amazing!", "I liked i
t", "One of the best movies","Fascinating plot")
departed_list