<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Maazin Ansari</title><link href="http://maazinansari.com/" rel="alternate"></link><link href="http://maazinansari.com/feeds/all.atom.xml" rel="self"></link><id>http://maazinansari.com/</id><updated>2023-11-02T00:00:00-05:00</updated><entry><title>Accounts - Gnucash with PostgreSQL</title><link href="http://maazinansari.com/posts/gnucash_002_accounts" rel="alternate"></link><published>2023-11-02T00:00:00-05:00</published><updated>2023-11-02T00:00:00-05:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2023-11-02:/posts/gnucash_002_accounts</id><summary type="html">&lt;p&gt;Explaining accounts in Gnucash&lt;/p&gt;</summary><content type="html">&lt;p&gt;The first step to managing your personal finances is to have a practical &lt;em&gt;chart of accounts&lt;/em&gt;. Think of all the financial institutions you interact with: banks, credit cards, your employer, utility companies, insurance providers. Each of them represents an account with a balance that increases or decreases over time. &lt;/p&gt;
&lt;h1&gt;Create an account&lt;/h1&gt;
&lt;p&gt;From the accounts tab in Gnucash, right click and select &lt;em&gt;New Account...&lt;/em&gt;. Your first one will be your main bank account, an asset account. Give it a name and confirm the currency. In the &lt;em&gt;Opening Balance&lt;/em&gt; tab, enter the current balance and today's date.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_002_accounts/create-account.png" title="create-account" alt="create-account" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_002_accounts/opening-balance.png" title="opening-balance" alt="opening-balance" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h2&gt;In the database&lt;/h2&gt;
&lt;p&gt;You can see your new account in the database by querying the &lt;code&gt;accounts&lt;/code&gt; table.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;SELECT * FROM accounts
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="../../static/gnucash_002_accounts/accounts-table.png" title="accounts-table" alt="accounts-table" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Notice your new account has a parent_guid that matches the guid of another account. This is how account hierarchies are maintained. &lt;/p&gt;
&lt;h1&gt;Types of accounts&lt;/h1&gt;
&lt;p&gt;To summarize the &lt;a href="https://www.gnucash.org/docs/v4/C/gnucash-guide.pdf"&gt;Gnucash Concepts Guide&lt;/a&gt;, everything in the accounting world can fit into five groups, or account types. Here are some ideas for accounts you can create. &lt;/p&gt;
&lt;p&gt;I will regularly update this page to provide links to more detailed posts for the examples below.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Assets&lt;ul&gt;
&lt;li&gt;&lt;a href="/gnucash-bank"&gt;cash, debit cards, checking and savings accounts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../posts/gnucash-investment"&gt;investment and retirement accounts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="posts/gnucash-loan"&gt;loans that are owed to you&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-fixed-asset"&gt;homes, vehicles, and valuable property&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Liabiliies&lt;ul&gt;
&lt;li&gt;&lt;a href="../gnucash-mortgage"&gt;mortgages&lt;/a&gt; and &lt;a href="../gnucash-loan"&gt;loans&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-credit-card"&gt;credit cards&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-bills"&gt;utility and medical bills&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Income&lt;ul&gt;
&lt;li&gt;&lt;a href="../gnucash-paycheck"&gt;Salary, wages, commission, bonuses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-paycheck"&gt;Employer contributions and reimbursements&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-insurance"&gt;Insurance claim payments&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-interest"&gt;Interest earned&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Expenses&lt;ul&gt;
&lt;li&gt;Living costs: rent, groceries, gasoline, utilities, &lt;a href="../gnucash-insurance"&gt;insurance premiums&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Everyday purchases: travel, entertainment, shopping&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-tax"&gt;Taxes&lt;/a&gt; and fees&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-interest"&gt;Interest paid&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="../gnucash-discount"&gt;Discounts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Equity&lt;ul&gt;
&lt;li&gt;Opening balances&lt;/li&gt;
&lt;li&gt;Everything else, technical accounts, miscellaneous&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If all these accounts seem like too much for you, just create the accounts you need now. Do not feel compelled to preemptively make accounts without any transactions to put in them. As you become more comfortable with the basic principles of Gnucash, you will be able to create and rearrange accounts to fit your needs.&lt;/p&gt;
&lt;h1&gt;Account codes&lt;/h1&gt;
&lt;p&gt;You may find it helpful to assign codes to your accounts. If you plan to use SQL for analysis, a practical coding can make it easier to group accounts together in your queries. For example, when I want to query all my credit card accounts I use the regular expression &lt;code&gt;^201/d00&lt;/code&gt; since I set up all my credit card accounts to start with 201. &lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_002_accounts/account-codes.png" title="account-codes" alt="Querying all my credit card accounts using the account code" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Account codes need not be entirely numeric. You can use abbreviations or shorthand codes. &lt;/p&gt;</content><category term="gnucash"></category><category term="sql"></category><category term="personal-finance"></category></entry><entry><title>Database Tables - Gnucash with PostgreSQL</title><link href="http://maazinansari.com/posts/gnucash_001_erd" rel="alternate"></link><published>2023-08-20T00:00:00-05:00</published><updated>2023-08-20T00:00:00-05:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2023-08-20:/posts/gnucash_001_erd</id><summary type="html">&lt;p&gt;Gnucash database entity relationship diagrams&lt;/p&gt;</summary><content type="html">&lt;p&gt;The following materials were created by me based on my own experience and observations of Gnucash. I have removed a lot of detail to make the diagrams easier to read.
A more complete entity relationship diagram exists on the official &lt;a href="https://wiki.gnucash.org/wiki/SQL#Entity_Relationship_Model"&gt;Gnucash Wiki&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Basic transactions&lt;/h1&gt;
&lt;p&gt;Basic transactions work like this: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A transaction row is created in &lt;code&gt;transactions&lt;/code&gt; with a new key. &lt;/li&gt;
&lt;li&gt;Two or more transaction splits are created in &lt;code&gt;splits&lt;/code&gt; with the same transaction key.&lt;/li&gt;
&lt;li&gt;These splits are each assigned an account from the &lt;code&gt;account&lt;/code&gt; table.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_001_erd/db_gnucash_basic_transactions.png" alt="Entity relationship diagram for basic transactions" style="display: block; scale: 75%; margin-left: -18%;"&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;splits&lt;/code&gt; table is at the center of this snowflake schema. It stores the details of every transaction split, such as the transaction it belongs to, the account, and the amount. &lt;/li&gt;
&lt;li&gt;The &lt;code&gt;transactions&lt;/code&gt; table is like the header table for &lt;code&gt;splits&lt;/code&gt;. It contains high-level information such as the date, currency, and description. &lt;/li&gt;
&lt;li&gt;The &lt;code&gt;accounts&lt;/code&gt; table is the main dimension table for &lt;code&gt;splits&lt;/code&gt;. It contains the account-level details, such as name, account code, and primary currency. &lt;/li&gt;
&lt;li&gt;The &lt;code&gt;commodities&lt;/code&gt; table contains currencies and traded commodities such as stocks. In this diagram, it is only used for currencies. &lt;/li&gt;
&lt;li&gt;The &lt;code&gt;slots&lt;/code&gt; table is used as a miscellaneous dimension table. It contains additional details for rows in other tables. 
I have included the &lt;code&gt;slots&lt;/code&gt; table three times in this diagram to show the different kinds of information it contains. For example, it can be linked to &lt;code&gt;transactions&lt;/code&gt; to get the transaction-level notes, or it can be linked to &lt;code&gt;accounts&lt;/code&gt; to get the account-level notes or the account color.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In Gnucash, globally unique identifiers (guid) are used as keys. Technically, their data type is varchar(32). This means they are strings of length 32. They are randomly generated and contain only the hex digits 0-9 and a-f.&lt;/p&gt;
&lt;h1&gt;Budgets&lt;/h1&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_001_erd/db_gnucash_budgets.png" alt="Entity relationship diagram for budgets" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Gnucash has a budgeting functionality that allows you to set budget amounts for each account across any time period. This is mainly tracked by four tables.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;budgets&lt;/code&gt; is the header table for the budgets. &lt;/li&gt;
&lt;li&gt;&lt;code&gt;recurrences&lt;/code&gt; contains the calendar settings for the budget. &lt;/li&gt;
&lt;li&gt;&lt;code&gt;budget_amounts&lt;/code&gt; contains the budget amount for each account during a particular period. &lt;/li&gt;
&lt;li&gt;&lt;code&gt;accounts&lt;/code&gt; is the same account table as before with the account-level details. &lt;/li&gt;
&lt;/ul&gt;
&lt;h1&gt;Scheduled transactions&lt;/h1&gt;
&lt;p&gt;&lt;img src="../../static/gnucash_001_erd/db_gnucash_schedxactions.png" title="center" alt="Entity relationship diagram for scheduled transactions" style="display: block; margin: 0; scale:75%; margin-left:-18%"&gt;&lt;/p&gt;
&lt;p&gt;Gnucash also allows you to create recurring transactions with the scheduled transactions editor. In the database, this process is a little complex. 
The tables &lt;code&gt;schedxactions&lt;/code&gt; and &lt;code&gt;recurrences&lt;/code&gt; contain the scheduling and calendar settings. 
You might notice the core &lt;code&gt;transactions-splits-accounts&lt;/code&gt; relationship from the first diagram. There are some important distinctions for scheduled transactions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The accounts, splits, and transactions here are templates that don't appear in the GUI &lt;/li&gt;
&lt;li&gt;The accounts are children of the &lt;em&gt;Template Root&lt;/em&gt; account rather than the &lt;em&gt;Root Account&lt;/em&gt;. Their names are randomly generated varchar(32) hex strings. &lt;/li&gt;
&lt;li&gt;The splits for each template transaction belong to one template account. Normally transactions contains splits for two different accounts.  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In addition to the scheduling tables and the core transaction relationship, the &lt;code&gt;slots&lt;/code&gt; table plays a major part in this functionality. It joins to &lt;code&gt;splits&lt;/code&gt; and to itself to get the key details about the scheduled transaction: the real accounts and the numeric amounts. &lt;/p&gt;
&lt;h1&gt;Currency rates&lt;/h1&gt;
&lt;p&gt;Coming soon...&lt;/p&gt;
&lt;h1&gt;Business tables&lt;/h1&gt;
&lt;p&gt;Coming much later...&lt;/p&gt;</content><category term="gnucash"></category><category term="sql"></category><category term="personal-finance"></category><category term="erd"></category></entry><entry><title>Setup - Gnucash with PostgreSQL</title><link href="http://maazinansari.com/posts/gnucash_000_setup" rel="alternate"></link><published>2023-08-07T00:00:00-05:00</published><updated>2023-08-07T00:00:00-05:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2023-08-07:/posts/gnucash_000_setup</id><summary type="html">&lt;p&gt;Setting up PostgreSQL and Gnucash&lt;/p&gt;</summary><content type="html">&lt;p&gt;This post is the first in a series of tutorials on personal finance with SQL. The goal is to teach technical data analysis techniques in a way that benefits you immediately. The datasets you interact with will be your own financial data, and the analyses you perform can be used for yourself.&lt;/p&gt;
&lt;h1&gt;Download and install&lt;/h1&gt;
&lt;p&gt;To get started, you will need to download the following software&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.gnucash.org/download.phtml"&gt;Gnucash&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.postgresql.org/download/"&gt;PostgreSQL&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;pgAdmin (or other SQL query tool)&lt;/li&gt;
&lt;li&gt;&lt;a href="https://postgresapp.com/"&gt;Postgres.app&lt;/a&gt; (recommended for macOS)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The installation instructions vary depending on your operating system. The official instructions tend to be easy to follow. There are also video tutorials available on YouTube.&lt;/p&gt;
&lt;h1&gt;Set up PostgreSQL&lt;/h1&gt;
&lt;p&gt;Follow the installation instructions for PostgreSQL and use the default settings. &lt;/p&gt;
&lt;p&gt;Depending on your operating system, you may need to download and install pgAdmin separately. If you are using macOS, I recommend you also install the Postgres.app. This will make it easier to connect to your Gnucash database in the future. &lt;/p&gt;
&lt;h2&gt;Open pgAdmin&lt;/h2&gt;
&lt;p&gt;You will need to set a password the first time you open pgAdmin. This is not the same as the postgres user password you set when you installed PostgreSQL. You will only use this password when you want to use pgAdmin.&lt;/p&gt;
&lt;p&gt;In the Browser panel, you will see one server &lt;em&gt;Local&lt;/em&gt; which has one database &lt;em&gt;postgres&lt;/em&gt;. There is also a &lt;em&gt;postgres&lt;/em&gt; role ("user") in the &lt;em&gt;Local&lt;/em&gt; server. To avoid confusion in the future, we will create a new role &lt;em&gt;u_gnucash&lt;/em&gt; and a new database &lt;em&gt;db_gnucash&lt;/em&gt; &lt;/p&gt;
&lt;h2&gt;Create a new role&lt;/h2&gt;
&lt;p&gt;Select the &lt;em&gt;postgres&lt;/em&gt; database and open a new query window. Create a new &lt;em&gt;u_gnucash&lt;/em&gt; role with the statement below&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;CREATE ROLE u_gnucash WITH
  LOGIN
  SUPERUSER
  INHERIT
  CREATEDB
  CREATEROLE
  NOREPLICATION
  PASSWORD &amp;#39;your password&amp;#39;;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The &lt;code&gt;PASSWORD&lt;/code&gt; parameter is optional. If you omit it in the statement, you can always set a password at a later time. &lt;/p&gt;
&lt;h2&gt;Create a new database&lt;/h2&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;CREATE DATABASE db_gnucash WITH 
    OWNER = u_gnucash
    ENCODING = &amp;#39;UTF8&amp;#39;
    LC_COLLATE = &amp;#39;en_US.UTF-8&amp;#39;
    LC_CTYPE = &amp;#39;en_US.UTF-8&amp;#39;
    TABLESPACE = pg_default
    CONNECTION LIMIT = -1;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This database will not have any tables or data yet. We will need to set up Gnucash next.&lt;/p&gt;
&lt;h1&gt;Set up Gnucash&lt;/h1&gt;
&lt;p&gt;Gnucash is an open source bookkeeping application that has a neat graphical user interface, and a simple database underneath. We will be taking advantage of both in later guides. Depending on the problem you are trying to solve, you might find the GUI is the better tool, and other times you might find it easier to look directly in the database.&lt;/p&gt;
&lt;p&gt;With Gnucash open click &lt;em&gt;File &amp;gt; Save As...&lt;/em&gt;. Change the data format from XML to Postgres. Enter the following connection details:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Host: &lt;code&gt;localhost&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Database: &lt;code&gt;db_gnucash&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Username: &lt;code&gt;u_gnucash&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Password: &lt;em&gt;The password you created above&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;If you are using macOS, make sure the server is still running in Postrgres.app&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Click Save As. Gnucash will automatically create the necessary tables to get started. &lt;/p&gt;
&lt;h1&gt;Check&lt;/h1&gt;
&lt;p&gt;To confirm the setup was successful, go back to pgAdmin and refresh db_gnucash. Expand the tree to &lt;em&gt;Schemas &amp;gt; public &amp;gt; Tables&lt;/em&gt; and you will see 24 tables.&lt;/p&gt;
&lt;p&gt;In the next post we will explore what these tables mean and how they are related to each other. &lt;/p&gt;</content><category term="gnucash"></category><category term="sql"></category><category term="personal-finance"></category></entry><entry><title>Duelling Idiots - Bulb</title><link href="http://maazinansari.com/posts/bulb" rel="alternate"></link><published>2019-03-05T00:00:00-06:00</published><updated>2019-03-05T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2019-03-05:/posts/bulb</id><summary type="html">&lt;p&gt;The glowing bulb problem from "Duelling Idiots and Other Probability Puzzlers"&lt;/p&gt;</summary><content type="html">&lt;p&gt;There are several parts to this problem, culminating with a Markov Chain.
So, I'll take it slow and only do the first part here.&lt;/p&gt;
&lt;h1&gt;The Problem&lt;/h1&gt;
&lt;p&gt;Imagine there are &lt;span class="math"&gt;\(N\)&lt;/span&gt; switches in series to form a row of switches.
Then, put &lt;span class="math"&gt;\(N\)&lt;/span&gt; such rows in parallel to form a sheet of &lt;span class="math"&gt;\(N^2\)&lt;/span&gt; switches.
Finally, put &lt;span class="math"&gt;\(N\)&lt;/span&gt; of these sheets in series, with a lightbulb, to form complicated circuit with
&lt;span class="math"&gt;\(N^3\)&lt;/span&gt; total switches.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/03-circuit/schematic.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;The above schematic shows what this circuit looks like when &lt;span class="math"&gt;\(N=3\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Each switch is, independently, open or closed, with probability &lt;span class="math"&gt;\(p\)&lt;/span&gt;.
What is the probability &lt;span class="math"&gt;\(P_1(N,p)\)&lt;/span&gt; that the bulb will glow?&lt;/p&gt;
&lt;p&gt;If the sheets are connected in parallel,
what is the probability &lt;span class="math"&gt;\(P_2(N,p)\)&lt;/span&gt; that the bulb will glow?&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/03-circuit/parallel-sheets.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h1&gt;Circuit Basics&lt;/h1&gt;
&lt;p&gt;The bulb will glow if the circuit is closed.
The circuit is closed if there is at least one unbroken path
from the negative terminal, through the switches, through the bulb, and to the positive terminal of the battery.&lt;/p&gt;
&lt;p&gt;In a row of switches in series, all switches must be closed.
When the rows are connected in parallel, at least one row in the sheet must be closed,
but it is not necessary for all rows to be closed. 
Similarly, when the sheets are connected in parallel, at least one must be closed.
When the sheets are connected in series, all sheets must be closed.&lt;/p&gt;
&lt;h1&gt;Analytical Solution&lt;/h1&gt;
&lt;p&gt;Now that we know how circuits work, we can start finding the exact solution. Let's start with the individual switches connected in series.&lt;/p&gt;
&lt;p&gt;An individual switch has a probability &lt;span class="math"&gt;\(p\)&lt;/span&gt; of being closed.
Now we connect &lt;span class="math"&gt;\(N\)&lt;/span&gt; independent and identical switches in series.
The probability the whole series is closed is &lt;/p&gt;
&lt;div class="math"&gt;$$
p_1 \times ... \times p_N =  \color{#377eb8}{p^N}
$$&lt;/div&gt;
&lt;p&gt;And the probability the series is open is just the opposite &lt;/p&gt;
&lt;div class="math"&gt;$$1-\color{#377eb8}{p^N}$$&lt;/div&gt;
&lt;p&gt;Now we connect &lt;span class="math"&gt;\(N\)&lt;/span&gt; of these series in parallel to make a sheet.
If zero series are closed, then the sheet is open.
If more than zero series are closed (i.e. at least one is closed), then the sheet is closed.
The probability of zero series closed (all series open) is &lt;/p&gt;
&lt;div class="math"&gt;$$(1-\color{#377eb8}{p^N})_1 \times ... \times (1-\color{#377eb8}{p^N})_N = \color{#d95f02}{(1-\color{#377eb8}{p^N})^N}$$&lt;/div&gt;
&lt;p&gt;This is also the probability of the sheet being open. 
And the probability the sheet is closed is the opposite &lt;/p&gt;
&lt;div class="math"&gt;$$
1 - \color{#d95f02}{(1-\color{#377eb8}{p^N})^N}
$$&lt;/div&gt;
&lt;p&gt;Almost there.&lt;/p&gt;
&lt;p&gt;Finally, we connect &lt;span class="math"&gt;\(N\)&lt;/span&gt; of these sheets to make an incredibly complicated circuit.
If we connect the sheets in series, all &lt;span class="math"&gt;\(N\)&lt;/span&gt; sheets must be closed.
Like we did in the first step, we can multiply together the probabilities of each sheet being closed &lt;/p&gt;
&lt;div class="math"&gt;$$
\begin{align*}
 P_1(N,p) 
 &amp;amp;= (1 - \color{#d95f02}{(1-\color{#377eb8}{p^N})^N})_1 \times ... \times (1 - \color{#d95f02}{(1-\color{#377eb8}{p^N})^N})_N  \\
 &amp;amp;= \bf{[1 - (1-p^N)^N]^N}
\end{align*}
$$&lt;/div&gt;
&lt;p&gt;If we connect the sheets in parallel, at least one sheet must be closed.
This one is trickier, because we need to think with opposites again.
The probability zero sheets are closed (all sheets open) is &lt;/p&gt;
&lt;div class="math"&gt;$$
\color{#d95f02}{(1-\color{#377eb8}{p^N})^N}_1 \times ... \times \color{#d95f02}{(1-\color{#377eb8}{p^N})^N}_N = (\color{#d95f02}{(1-\color{#377eb8}{p^N})^N})^N
$$&lt;/div&gt;
&lt;p&gt;And the probability more than zero sheets (at least one) are closed is the opposite&lt;/p&gt;
&lt;div class="math"&gt;$$
P_2(N,p) = \bf{1 - (1-p^N)^{N^2}}
$$&lt;/div&gt;
&lt;h1&gt;Series vs. Parallel&lt;/h1&gt;
&lt;p&gt;The two probabilities look similar, but they are very different. 
The plot below shows how &lt;span class="math"&gt;\(P_1\)&lt;/span&gt; and &lt;span class="math"&gt;\(P_2\)&lt;/span&gt; compare for different values of &lt;span class="math"&gt;\(N\)&lt;/span&gt; and &lt;span class="math"&gt;\(p\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/03-circuit/plot_p_lines.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Connecting the sheets in parallel gives the bulb a much higher chance of glowing than connecting them in series, for any value of &lt;span class="math"&gt;\(N\)&lt;/span&gt; and &lt;span class="math"&gt;\(p\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;I added the red and blue lines to show two more scenarios: putting the &lt;span class="math"&gt;\(N^3\)&lt;/span&gt; switches in parallel (red) 
and putting the &lt;span class="math"&gt;\(N^3\)&lt;/span&gt; switches in series (blue). The difference between series and parallel is more pronounced. It is extremely unlikely for the bulb to glow if the switches are in series, unless &lt;span class="math"&gt;\(p\)&lt;/span&gt; is almost 1. Conversely, the bulb will almost always glow if the switches are in parallel, unless &lt;span class="math"&gt;\(p\)&lt;/span&gt; is almost 0.&lt;/p&gt;
&lt;p&gt;For a fixed &lt;span class="math"&gt;\(p\)&lt;/span&gt;, &lt;span class="math"&gt;\(P_1\)&lt;/span&gt; decreases sharply as &lt;span class="math"&gt;\(N\)&lt;/span&gt; increases. This makes sense because it becomes less likely that all the sheets are closed as we add more sheets to the series. &lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/03-circuit/plot_N_bars.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;What I found surprising is that &lt;span class="math"&gt;\(P_2\)&lt;/span&gt; increases first, then decreases after a certain &lt;span class="math"&gt;\(N\)&lt;/span&gt;. My interpretation is that when there are more sheets, it is more likely that at least one will be closed. However, each sheet also has &lt;span class="math"&gt;\(N\)&lt;/span&gt; rows in series, and when a row gets longer, it is less likely all switches in the row will be closed. Eventually, the effect of longer series outweighs the effect of more sheets in parallel.&lt;/p&gt;
&lt;p&gt;Note that &lt;span class="math"&gt;\(P_1\)&lt;/span&gt; and &lt;span class="math"&gt;\(P_2\)&lt;/span&gt; are equal to &lt;span class="math"&gt;\(p\)&lt;/span&gt; when &lt;span class="math"&gt;\(N=1\)&lt;/span&gt;, because when &lt;span class="math"&gt;\(N=1\)&lt;/span&gt;, there is just one switch in the circuit.&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category><category term="Probability"></category><category term="DI"></category></entry><entry><title>Visualizing Log-transformed Data</title><link href="http://maazinansari.com/posts/location-history-log-transform" rel="alternate"></link><published>2018-07-18T00:00:00-05:00</published><updated>2018-07-18T00:00:00-05:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-07-18:/posts/location-history-log-transform</id><summary type="html">&lt;p&gt;Implementation and interpretation of log-transformed data&lt;/p&gt;</summary><content type="html">&lt;p&gt;The first thing I do when I have a clean data set is plot the variables (columns) as histograms. Along with the standard summary statistics, histograms give a quick overview of the distribution of the data. Sometimes the data spans several orders of magnitude, and I can't see any pattern from the histogram or the summary statistics. In these cases, the histogram of the logarithm of the data may be useful.&lt;/p&gt;
&lt;p&gt;One downside of log-transformations is the loss of human interpretability. To maintain some interpretability, I use untransformed labels instead of the transformed labels that would appear by default.&lt;/p&gt;
&lt;p&gt;I am using my personal Google location history data. This is my first post using this data set. There's a lot more that can be done with it, so I plan on writing more in-depth analyses in the future. A quick Google search for "google location history data" will yield countless blog posts showing you how to obtain, clean, and analyze your own location history from Google. &lt;a href="http://emelineliu.com/2016/10/21/LocationHistory/"&gt;Here's one I used.&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;Untransformed data&lt;/h1&gt;
&lt;p&gt;With this data set, I first wanted to understand how frequently I was being tracked. Each observation (row) has a timestamp. The difference in time between two consecutive observations will give me the time between each record. The new variable &lt;code&gt;t_diff_s&lt;/code&gt; is the time in seconds since the previous observation, i.e. the current time minus the lag. I manually assign &lt;code&gt;0&lt;/code&gt; to the first observation, since there is no previous row to subtract. &lt;/p&gt;
&lt;p&gt;&lt;em&gt;I could have also calculated the time until the next observation, i.e. the lead minus the current time, and assigned 0 to the last observation. This is a decision that comes down to how you want to interpret the data.&lt;/em&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s &lt;span class="o"&gt;=&lt;/span&gt; PTS_df&lt;span class="o"&gt;$&lt;/span&gt;time &lt;span class="o"&gt;-&lt;/span&gt; lag&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;time&lt;span class="p"&gt;)&lt;/span&gt;
PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;as.double&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;From the summary, we can see right away &lt;code&gt;t_diff_s&lt;/code&gt; has a very large range. Time between records is anywhere between a few milliseconds and several hours.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kt"&gt;data.frame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;min &lt;span class="o"&gt;=&lt;/span&gt; PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;head&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
           max &lt;span class="o"&gt;=&lt;/span&gt; PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;3&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##           min      max
## 1 0.000000000 52432.46
## 2 0.003000021 54089.61
## 3 0.005000114 68356.00
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     0.0   132.4   199.1  1400.7   585.3 68356.0
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The wide range and strong right skew is seen in the histogram, too. We can also see that most observations were sampled less than 200 seconds apart.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;hist&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;,&lt;/span&gt;
     breaks &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     main &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Histogram of\ntime between observations&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     xlab &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;time in seconds&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="../../static/location-history/standard_hist.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h1&gt;Transformed data&lt;/h1&gt;
&lt;p&gt;The above histogram isn't very useful because the visible time scale is on the order of a few hours. Most of the values are on the order of just a few minutes, so it would be more helpful to see the data at this granularity, while also preserving the full range. A reasonable solution would be to plot the histogram of &lt;code&gt;log(t_diff_s)&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;hist&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;),&lt;/span&gt;
     breaks &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     main &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Histogram of\nlog(time between observations)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     xlab &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;log(time)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="../../static/location-history/log_hist.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h1&gt;Better labels&lt;/h1&gt;
&lt;p&gt;By scaling the x-axis logarithmically, smaller values are more dispersed and larger values are bunched together. The distribution looks much less skewed now, but the labels on the x-axis don't make sense. To make the axis more clear, I place labels at predetermined points with the &lt;code&gt;axis()&lt;/code&gt; function. The location of the labels need to be log-transformed. The labels' text are untransformed.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;time_hist &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;x&lt;span class="p"&gt;,&lt;/span&gt; col &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    h &lt;span class="o"&gt;=&lt;/span&gt; hist&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;x&lt;span class="p"&gt;),&lt;/span&gt;
             axes &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;FALSE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
             main &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Histogram of\nlog(time between observations)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
             xlab &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;time between points&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
             col &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;col&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
             breaks &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
    axis&lt;span class="p"&gt;(&lt;/span&gt;side &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;

         &lt;span class="c1"&gt;# labels at log-transformed points &lt;/span&gt;
         at &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;0.1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;120&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;3600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;21600&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt; 

         &lt;span class="c1"&gt;# text of labels is untransformed points&lt;/span&gt;
         labels &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;paste0&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;0.1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;120&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;3600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;21600&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;s&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;

         cex.axis &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.75&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         padj &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;-2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         hadj &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         las &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    axis&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kr"&gt;return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;h&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

h &lt;span class="o"&gt;=&lt;/span&gt; time_hist&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="../../static/location-history/time_hist.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Now we can better interpret the distribution of &lt;code&gt;t_diff_s&lt;/code&gt;. Most values fall between two and ten minutes (120 — 600 seconds). The most common sampling interval lengths are between 134 and 164 seconds. A few observations were taken less than one second apart. Some observations were recorded over 6 hours (21600 seconds) after the previous one.&lt;/p&gt;
&lt;p&gt;When we think about time, especially the time that &lt;code&gt;t_diff_s&lt;/code&gt; represents, the log-transformed histogram fits our intuition the best. There is an apparent pattern that also coincides with how we might subconsciously think about the data.&lt;/p&gt;
&lt;p&gt;The range of the x-axis of the untransformed histogram leads us to mentally group the values into hours-long clusters. A millisecond (0.1s), 5 minutes (300s), and one hour (3600s) are all grouped together in the lowest group, while five hours (18000s) and fifteen hours (54000s) are visually separate.  &lt;/p&gt;
&lt;p&gt;While this isn't necessarily wrong, it is an unusual way to think about time. The log-transformed histogram data better shows us visual groupings that we are familiar with: milliseconds, seconds, minutes, and hours.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;hcols &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;rep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;#FFFFFF&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kp"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;h&lt;span class="o"&gt;$&lt;/span&gt;mids&lt;span class="p"&gt;))&lt;/span&gt;
hcols&lt;span class="p"&gt;[&lt;/span&gt;h&lt;span class="o"&gt;$&lt;/span&gt;mids &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#edf8fb&amp;quot;&lt;/span&gt;
hcols&lt;span class="p"&gt;[&lt;/span&gt;h&lt;span class="o"&gt;$&lt;/span&gt;mids &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#bdc9e1&amp;quot;&lt;/span&gt;
hcols&lt;span class="p"&gt;[&lt;/span&gt;h&lt;span class="o"&gt;$&lt;/span&gt;mids &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#67a9cf&amp;quot;&lt;/span&gt;
hcols&lt;span class="p"&gt;[&lt;/span&gt;h&lt;span class="o"&gt;$&lt;/span&gt;mids &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;60&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="m"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#02818a&amp;quot;&lt;/span&gt;
h &lt;span class="o"&gt;=&lt;/span&gt; time_hist&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;,&lt;/span&gt; col &lt;span class="o"&gt;=&lt;/span&gt; hcols&lt;span class="p"&gt;)&lt;/span&gt;
legend&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;left&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       legend &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;milliseconds&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;seconds&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;minutes&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;hours&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
       fill &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;#edf8fb&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#bdc9e1&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#67a9cf&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;#02818a&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
       bty &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;n&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="../../static/location-history/bins.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;For future analyses, this information will help me determine which observations are reliable enough to keep, and which ones I can remove due to redundancy.&lt;/p&gt;
&lt;p&gt;The code I used for this is available on my &lt;a href="https://github.com/maazinansari/maazinansari/tree/master/content/R/location-history/"&gt;GitHub&lt;/a&gt;. I also included a simulated data set, &lt;code&gt;timestamps.csv&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;d &lt;span class="o"&gt;=&lt;/span&gt; density&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="c1"&gt;# means are directly sampled&lt;/span&gt;
logmeans &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;sample&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;x &lt;span class="o"&gt;=&lt;/span&gt; PTS_df&lt;span class="o"&gt;$&lt;/span&gt;t_diff_s&lt;span class="p"&gt;,&lt;/span&gt; size &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; replace &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; 
&lt;span class="c1"&gt;# standard deviation is the kernel bandwidth&lt;/span&gt;
logx &lt;span class="o"&gt;=&lt;/span&gt; rnorm&lt;span class="p"&gt;(&lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; mean &lt;span class="o"&gt;=&lt;/span&gt; logmeans&lt;span class="p"&gt;,&lt;/span&gt; sd &lt;span class="o"&gt;=&lt;/span&gt; d&lt;span class="o"&gt;$&lt;/span&gt;bw&lt;span class="p"&gt;)&lt;/span&gt;

x &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;logx&lt;span class="p"&gt;)&lt;/span&gt;
timestamps &lt;span class="o"&gt;=&lt;/span&gt; ymd_hms&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;2018-01-01 00:00:00.00&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; seconds&lt;span class="p"&gt;(&lt;/span&gt;x&lt;span class="p"&gt;)&lt;/span&gt;
write.csv&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;timestamps&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;timestamps.csv&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;</content><category term="R"></category><category term="Statistics"></category><category term="GIS"></category><category term="QGIS"></category><category term="time series"></category><category term="Google"></category></entry><entry><title>Duelling Idiots</title><link href="http://maazinansari.com/posts/idiots-2" rel="alternate"></link><published>2018-03-05T00:00:00-06:00</published><updated>2018-03-05T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-03-05:/posts/idiots-2</id><summary type="html">&lt;p&gt;A deadly duel between two idiots. How fair is it?&lt;/p&gt;</summary><content type="html">&lt;p&gt;The previous post was just a warmup for the rest of the book. This is the first real puzzle. The code for my solutions and the book's original solution are available on &lt;a href="https://github.com/maazinansari/Duelling-Idiots"&gt;my GitHub&lt;/a&gt;. &lt;/p&gt;
&lt;h1&gt;The Problem&lt;/h1&gt;
&lt;p&gt;Two individuals, &lt;em&gt;A&lt;/em&gt; and &lt;em&gt;B&lt;/em&gt;, will participate in a duel, which has the following setup:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A six-chamber gun is loaded with one bullet. The cylinder is spun so the bullet is essentially randomized. &lt;/li&gt;
&lt;li&gt;&lt;em&gt;A&lt;/em&gt; aims at &lt;em&gt;B&lt;/em&gt; and pulls the trigger. The gun has a 1/6 chance of firing the bullet. &lt;/li&gt;
&lt;li&gt;If the gun does not fire, &lt;em&gt;B&lt;/em&gt; takes the gun, spins the cylinder, then pulls the trigger at &lt;em&gt;A&lt;/em&gt;. 
Again, the gun has a 1/6 chance of firing.&lt;/li&gt;
&lt;li&gt;The duelists take turns spinning the cylinder and pulling the trigger until the bullet is fired.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The problem asks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;What is the probability &lt;em&gt;A&lt;/em&gt; wins the duel?&lt;/li&gt;
&lt;li&gt;What is the expected length of the duel? That is, how many trigger pulls / turns will the duel last?&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;Analytical Solution&lt;/h1&gt;
&lt;p&gt;On each of &lt;em&gt;A&lt;/em&gt;'s turns, There is a 1/6 chance &lt;em&gt;A&lt;/em&gt; wins and a 5/6 chance the duel continues. &lt;em&gt;A&lt;/em&gt; can only win on an odd-numbered turn (1, 3, 5, ...), and &lt;em&gt;B&lt;/em&gt; can only win on an even-numbered turn (2, 4, 6, ...). &lt;em&gt;A&lt;/em&gt; cannot win if &lt;em&gt;B&lt;/em&gt; wins first. The probability &lt;em&gt;A&lt;/em&gt; wins is the total probability of winning on any odd-numbered turn. This can be expressed as the infinite sum&lt;/p&gt;
&lt;p&gt;\begin{align*}&lt;/p&gt;
&lt;p&gt;P(A) = &amp;amp; \frac{1}{6} + &amp;amp;&amp;amp; \text{A wins on turn 1}\
        &amp;amp; \frac{5}{6}&lt;em&gt;\frac{5}{6}&lt;/em&gt;\frac{1}{6} + &amp;amp;&amp;amp; \text{A misses, B misses, A wins on turn 3}\
        &amp;amp; \frac{5}{6}&lt;em&gt;\frac{5}{6}&lt;/em&gt;\frac{5}{6}&lt;em&gt;\frac{5}{6}&lt;/em&gt;\frac{1}{6} + 
        &amp;amp;&amp;amp; \text{A misses, B misses, A misses, B misses, A wins on turn 5}\\
        &amp;amp; ...
\end{align*}&lt;/p&gt;
&lt;div class="math"&gt;$$
 P(A) = \sum_{i=0}^{\infty}
 \Big(\frac{5}{6}\Big)^{2i}
 \Big(\frac{1}{6}\Big)
$$&lt;/div&gt;
&lt;p&gt;This is a geometric series, so it must converge. Factoring out &lt;span class="math"&gt;\(\frac{1}{6}\)&lt;/span&gt; gives &lt;/p&gt;
&lt;div class="math"&gt;$$
\begin{align*}
 P(A) 
 &amp;amp;= \frac{1}{6}\sum_{i=0}^{\infty} \Big(\frac{5}{6}\Big)^{2i} \\
 &amp;amp;= \frac{1}{6}\sum_{i=0}^{\infty} \Big(\Big(\frac{5}{6}\Big)^2\Big)^{i} \\
 &amp;amp;= \frac{1}{6}\sum_{i=0}^{\infty} \Big(\frac{25}{36}\Big)^{i} \\\\
 &amp;amp;= \frac{1}{6}\frac{1}{1-\frac{25}{36}} = \frac{1}{6}\frac{36}{11} \\
 P(A) &amp;amp;= \frac{6}{11} \approx 0.54545
\end{align*}
$$&lt;/div&gt;
&lt;p&gt;So, &lt;em&gt;A&lt;/em&gt; has a slight advantage over &lt;em&gt;B&lt;/em&gt; in this duel.&lt;/p&gt;
&lt;p&gt;The answer to the second question is a lot easier. This duel is a sequence of independent Bernoulli trials (&lt;span class="math"&gt;\(p=\frac{1}{6}\)&lt;/span&gt;). So, the number of trials, or turns, until the bullet is fired (a "success") follows a geometric distribution. The expected value of a geometric distribution is 
&lt;span class="math"&gt;\(\frac{1}{p}=6\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;I used the following code to simulate a duel. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kp"&gt;set.seed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;20180207&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# one duel ----&lt;/span&gt;
did_fire &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;prob &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="m"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    shot &lt;span class="o"&gt;=&lt;/span&gt; runif&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kr"&gt;return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shot &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; prob&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

duel &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooters &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;B&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    turn &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
    nshooters &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooters&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# repeat until a shot is fired&lt;/span&gt;
    &lt;span class="kr"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;# first shooter is A (2 - 1 mod 2 = 1)&lt;/span&gt;
        &lt;span class="c1"&gt;# second shooter is B (2 - 2 mod 2 = 2)&lt;/span&gt;
        turn &lt;span class="o"&gt;=&lt;/span&gt; turn &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# pass gun to next shooter&lt;/span&gt;
        shooter &lt;span class="o"&gt;=&lt;/span&gt; shooters&lt;span class="p"&gt;[&lt;/span&gt;nshooters &lt;span class="o"&gt;-&lt;/span&gt; turn &lt;span class="o"&gt;%%&lt;/span&gt; nshooters&lt;span class="p"&gt;]&lt;/span&gt;

        &lt;span class="c1"&gt;# pull trigger&lt;/span&gt;
        &lt;span class="kr"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; did_fire&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="kr"&gt;return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooter&lt;span class="p"&gt;,&lt;/span&gt; turn&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;# result is 2 x N matrix. Row 1 is winner. Row 2 is number of turns.&lt;/span&gt;
N &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;10000&lt;/span&gt;
simulations &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;replicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;N&lt;span class="p"&gt;,&lt;/span&gt; duel&lt;span class="p"&gt;(),&lt;/span&gt; simplify &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# results ----&lt;/span&gt;
&lt;span class="c1"&gt;# How many times A won&lt;/span&gt;
a_1 &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;simulations&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Average number of turns &lt;/span&gt;
average_1 &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;unlist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;simulations&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,]))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The plots below show the frequencies of a duelist winning on a particular turn. 
The one on the left is from my simulation. The one on the right is based on the book's simulation. &lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/02-idiots/plot1.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;I get the same results as the book, albeit a bit slower.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="left"&gt;&lt;/th&gt;
&lt;th align="right"&gt;prob&lt;/th&gt;
&lt;th align="right"&gt;average&lt;/th&gt;
&lt;th align="right"&gt;time&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="left"&gt;nahin&lt;/td&gt;
&lt;td align="right"&gt;0.5410000&lt;/td&gt;
&lt;td align="right"&gt;5.9364&lt;/td&gt;
&lt;td align="right"&gt;0.3570000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;me&lt;/td&gt;
&lt;td align="right"&gt;0.5514000&lt;/td&gt;
&lt;td align="right"&gt;5.9644&lt;/td&gt;
&lt;td align="right"&gt;0.4325931&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;theoretical&lt;/td&gt;
&lt;td align="right"&gt;0.5454545&lt;/td&gt;
&lt;td align="right"&gt;6.0000&lt;/td&gt;
&lt;td align="right"&gt;NA&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h1&gt;New Rules&lt;/h1&gt;
&lt;p&gt;To give &lt;em&gt;B&lt;/em&gt; a more fair chance the rules are modified. On the first turn &lt;em&gt;A&lt;/em&gt; pulls the trigger once. The cylinder is spun and &lt;em&gt;B&lt;/em&gt; pulls the trigger twice. &lt;em&gt;A&lt;/em&gt; pulls three times, &lt;em&gt;B&lt;/em&gt; pulls four, and so on until there is a winner. By these rules, the duel will last at most 6 turns.&lt;/p&gt;
&lt;p&gt;With these new rules, what is the probability &lt;em&gt;A&lt;/em&gt; wins the duel?&lt;/p&gt;
&lt;p&gt;It's harder to solve this problem analytically. This is where simulations become useful. My simulation below simulates a duel 10,000 times and records the winners. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;duel_2 &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooters &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;B&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; prob &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="m"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    p &lt;span class="o"&gt;=&lt;/span&gt; prob
    turn &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
    pulls &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
    nshooters &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooters&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# repeat until a shot is fired&lt;/span&gt;
    &lt;span class="kr"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;# first shooter is A (2 - 1 mod 2 = 1)&lt;/span&gt;
        &lt;span class="c1"&gt;# second shooter is B (2 - 2 mod 2 = 2)&lt;/span&gt;
        turn &lt;span class="o"&gt;=&lt;/span&gt; turn &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# pass gun to next shooter&lt;/span&gt;
        pulls &lt;span class="o"&gt;=&lt;/span&gt; turn &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;turn &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt; &lt;span class="c1"&gt;# shooter gets same number of pulls  + 1&lt;/span&gt;
        shooter &lt;span class="o"&gt;=&lt;/span&gt; shooters&lt;span class="p"&gt;[&lt;/span&gt;nshooters &lt;span class="o"&gt;-&lt;/span&gt; turn &lt;span class="o"&gt;%%&lt;/span&gt; nshooters&lt;span class="p"&gt;]&lt;/span&gt;

        &lt;span class="c1"&gt;# pull trigger&lt;/span&gt;
        &lt;span class="kr"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; did_fire&lt;span class="p"&gt;(&lt;/span&gt;prob &lt;span class="o"&gt;=&lt;/span&gt; p&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="kr"&gt;return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;shooter&lt;span class="p"&gt;,&lt;/span&gt; turn&lt;span class="p"&gt;,&lt;/span&gt; pulls&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="kr"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            p &lt;span class="o"&gt;=&lt;/span&gt; p &lt;span class="o"&gt;+&lt;/span&gt; prob
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

simulations_2 &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;replicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;N&lt;span class="p"&gt;,&lt;/span&gt; duel_2&lt;span class="p"&gt;(),&lt;/span&gt; simplify &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# results ----&lt;/span&gt;
&lt;span class="c1"&gt;# How many times A won&lt;/span&gt;
a_2 &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;simulations_2&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The book's solution is a little more abstract, and it runs much faster. Instead of simulating duels and counting wins, it simulates an infinite sum as the total probability &lt;em&gt;A&lt;/em&gt; wins, and checks for convergence. Still, our answers are similar: &lt;em&gt;A&lt;/em&gt; has a 52% chance of winning the duel.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="left"&gt;&lt;/th&gt;
&lt;th align="right"&gt;prob&lt;/th&gt;
&lt;th align="right"&gt;time&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="left"&gt;nahin&lt;/td&gt;
&lt;td align="right"&gt;0.5239191&lt;/td&gt;
&lt;td align="right"&gt;0.0140000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;me&lt;/td&gt;
&lt;td align="right"&gt;0.5267000&lt;/td&gt;
&lt;td align="right"&gt;0.1816361&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category><category term="Probability"></category><category term="DI"></category></entry><entry><title>Duelling Idiots - Introduction</title><link href="http://maazinansari.com/posts/idiots-1" rel="alternate"></link><published>2018-02-12T00:00:00-06:00</published><updated>2018-02-12T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-02-12:/posts/idiots-1</id><summary type="html">&lt;p&gt;Getting started with "Duelling Idiots and Other Probability Puzzlers"&lt;/p&gt;</summary><content type="html">&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;A few years ago I found a book at a bookstore. The book, &lt;em&gt;Duelling Idiots and Other Probability Puzzlers&lt;/em&gt; by Paul J. Nahin, is a collection of probability puzzles. I recently started going through these puzzles and decided to document my progress and share my solutions. &lt;/p&gt;
&lt;p&gt;This is the first in a series of posts where I solve the problems from the book. I'll solve them analytically first, then verify them with simulations. Nahin provided MATLAB code for the solutions, so I will also try to rewrite his original MATLAB code in R. My solutions will be added to 
&lt;a href="https://github.com/maazinansari/Duelling-Idiots"&gt;GitHub&lt;/a&gt; as I complete them.&lt;/p&gt;
&lt;p&gt;These puzzles are a little more advanced than the classic balls-in-the-urn or poker hand problems They require basic knowledge of calculus and advanced understanding of probability and statistics. &lt;/p&gt;
&lt;p&gt;With that said, though, the first problem is a warm-up, so its solution isn't as long or complicated as the others.&lt;/p&gt;
&lt;h1&gt;The Embarrasing Question&lt;/h1&gt;
&lt;p&gt;Researchers are asking subjects an embarrasing Yes/No question. To ensure the subjects don't lie, the team sets up the following surveying procedure:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Subject enters a private room with a piece of paper, and flips a fair coin&lt;ul&gt;
&lt;li&gt;If heads: Write the answer (Yes/No) on the paper&lt;/li&gt;
&lt;li&gt;If tails: Flip the coin again&lt;ul&gt;
&lt;li&gt;If heads: Write "Yes" on the paper&lt;/li&gt;
&lt;li&gt;If tails: Write "No" on the paper&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The subject turns in a piece of paper with a "Yes" or "No" on it, not knowing the results of the coin flip(s)&lt;/li&gt;
&lt;li&gt;Once all subjects turn in their papers, the researchers estimate &lt;span class="math"&gt;\(p\)&lt;/span&gt;, the proportion who truthfully answered "Yes" to the question. &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The researchers have 6,230 papers with "Yes" written on them, and 3,770 with "No". What is &lt;span class="math"&gt;\(p\)&lt;/span&gt;?&lt;/p&gt;
&lt;p&gt;The procedure is outlined in the probability tree below:&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/01-embarrasing-question/embarrasing-question.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;The tree assumes the coin flips are independent of each other, and are independent of the subjects' response to the question. The black numbers on each branch indicate the conditional probability of the event occuring. The red numbers indicate the joint probability of each of the four outcomes.&lt;/p&gt;
&lt;p&gt;We want to solve for &lt;span class="math"&gt;\(p\)&lt;/span&gt;, which is &lt;span class="math"&gt;\(P(\text{Yes} | \text{heads first})\)&lt;/span&gt;.
We are given &lt;span class="math"&gt;\(P(\text{Yes}) = \frac{6230}{10000}\)&lt;/span&gt; and we know a coin lands on heads with probability 0.5.&lt;/p&gt;
&lt;div class="math"&gt;$$
\begin{align*}
P(\text{Yes}) &amp;amp;= P(\text{heads first}\cap \text{Yes} ) + P(\text{heads second}) &amp;amp;= 6230/10000 \\
&amp;amp;        = 0.5p + 0.25 &amp;amp;= 6230/10000 \\
\end{align*}
$$&lt;/div&gt;
&lt;p&gt;
Solving for &lt;span class="math"&gt;\(p\)&lt;/span&gt;: &lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(p = 0.746\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;To verify the solution, here is a simulation of the problem, using the &lt;span class="math"&gt;\(p=0.746\)&lt;/span&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;simulate_EQ &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.746&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; N &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;10000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    pop &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;sample&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;yes&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;no&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; size &lt;span class="o"&gt;=&lt;/span&gt; N&lt;span class="p"&gt;,&lt;/span&gt; prob &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;p&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;p&lt;span class="p"&gt;),&lt;/span&gt; replace &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    results &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;rep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;no&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; N&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kr"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;i &lt;span class="kr"&gt;in&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;N&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        flip1 &lt;span class="o"&gt;=&lt;/span&gt; rbinom&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; size &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# 1 = heads, 0 = tails&lt;/span&gt;
        &lt;span class="kr"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;flip1&lt;span class="p"&gt;)&lt;/span&gt; results&lt;span class="p"&gt;[&lt;/span&gt;i&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; pop&lt;span class="p"&gt;[&lt;/span&gt;i&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="kr"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            flip2 &lt;span class="o"&gt;=&lt;/span&gt; rbinom&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; size &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="kr"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;flip2&lt;span class="p"&gt;)&lt;/span&gt; results&lt;span class="p"&gt;[&lt;/span&gt;i&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;yes&amp;quot;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="kr"&gt;return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;results&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

s &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;simulate_EQ&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;yes&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kp"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;s&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;## [1] 6228
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The simulation produces 6228 "Yes"s, very close the original problem's 6230. &lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category><category term="Probability"></category><category term="DI"></category></entry><entry><title>Un Año de Despacito</title><link href="http://maazinansari.com/posts/despacito-1-es" rel="alternate"></link><published>2018-01-14T00:00:00-06:00</published><updated>2018-01-14T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-01-14:/posts/despacito-1-es</id><summary type="html">&lt;p&gt;Un análysis de vistas de un videoclip&lt;/p&gt;</summary><content type="html">&lt;p&gt;La canción de Luis Fonsi, &lt;em&gt;Despacito&lt;/em&gt; ft. Daddy Yankee fue la canción de 2017. Lanzado en el principio de enero, la canción fue un éxito en Latinoamérica. Después de que se involucró Justin Bieber, dominaba las listas musicales alrededor del mundo.&lt;/p&gt;
&lt;p&gt;El videoclip de la versión original se publicó en YouTube el 12 de enero, 2017, hace un año. En solo 97 días, el vídeo recibió un mil millones de vistas. El 4 de agosto- solo 7 meses después de su publicación- el vídeo se convirtió en el primer vídeo en la historia de YouTube en alcanzar 3 mil millones de vistas. &lt;/p&gt;
&lt;p&gt;En este artículo voy a analizar cómo el videoclip creció tan rápido. Identifico las tendencias semanales y los momentos cuando las vistas crecían más rápido. Actualmente, no tengo mucha experiencia con las series temporales, así que esto será principalmente un análysis visual.&lt;/p&gt;
&lt;p&gt;Los datos, scripts, y gráficos adicionales están disponibles en &lt;a href="https://github.com/maazinansari/maazinansari/tree/master/content/R/despacito"&gt;mi GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Obtener los datos&lt;/h1&gt;
&lt;p&gt;YouTube ofrece estadísticas del vídeo en algunos vídeos. No estoy seguro de qué determina si un vídeo tiene las estadísticas activadas, pero parece que la mayoría de los videoclips de canciones las tienen. Esto es el gráfico de vistas diarias de Despacito:&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/yt-viz.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Podemos extraer los datos del código HTML.&lt;/p&gt;
&lt;p&gt;Es importante notar que las estadísticas del vídeo solo están disponibles en el diseño de YouTube anterior. Por alguna razón, YouTube quitó las estadísticas del vídeo en su nuevo diseño.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/oldtube.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;img src="../../static/despacito/newtube.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Cuando estás en la página del videoclip y ya has abierto las estadísticas del vídeo, haz clic con el botón secundario alrededor del gráfico y elige Inspect Element. Busca &lt;code&gt;stats-chart-gviz&lt;/code&gt; en el código HTML. Haz clic en las flechas hasta que encuentres la etiqueta &lt;code&gt;&amp;lt;table&amp;gt;&lt;/code&gt;. Haz clic con el botón secundario y elige Copy &amp;gt; Copy element y pégalo en un editor de texto y guardar como un archivo .html.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/html-elements.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h1&gt;Limpiar los datos&lt;/h1&gt;
&lt;p&gt;Ahora nuestros datos están en forma de una tabla HTML. Tenemos que obtener las fechas y los valores de la tabla para hacer nuestros proprios gráficos. Necesitamos el paquete &lt;code&gt;XML&lt;/code&gt; para esto. Específicamente, necesitamos la función &lt;code&gt;readHTMLTable()&lt;/code&gt; para leer los datos como una hoja de datos. Luego, creamos nuevas columnas &lt;code&gt;date&lt;/code&gt; y &lt;code&gt;views&lt;/code&gt; que contienen las fechas y los números de vistas en formatos adecuados. &lt;/p&gt;
&lt;p&gt;Es importante notar que yo extraí los datos de la página inglés de YouTube. Los scripts en GitHub en su forma actual no funcionan si extraes los datos de YouTube de otro idioma.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# Cleaning ----&lt;/span&gt;
&lt;span class="c1"&gt;# This script only works for data taken from the English language YouTube site.&lt;/span&gt;
despacito_table &lt;span class="o"&gt;=&lt;/span&gt; readHTMLTable&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;despacito_table.html&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
despacito_df &lt;span class="o"&gt;=&lt;/span&gt; despacito_table&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;strptime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;as.character&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;%b %d, %Y&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;as.Date&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;gsub&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;,&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;as.numeric&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Añadimos más columnas para facilitar el análysis y producir gråficos.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# Cumulative views&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;cumviews&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;cumsum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;

&lt;span class="c1"&gt;# Change in views from previous day&lt;/span&gt;
change &lt;span class="o"&gt;=&lt;/span&gt; despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;change&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; change

&lt;span class="c1"&gt;# Add year, month, day of week&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;year&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; year&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;month&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; month&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;wday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;factor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;weekdays&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]),&lt;/span&gt;
                           levels&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Monday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Tuesday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Wednesday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Thursday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Friday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Saturday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Sunday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;h1&gt;Análysis&lt;/h1&gt;
&lt;p&gt;Ahora tenemos los datos limpiados, y podemos producir algunos gráficos.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/views-per-day.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;img src="../../static/despacito/total.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Estos gráficos son los mismos que produce YouTube, con ciertos hitos marcados. Podemos ver algunas pautas interesantes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Picos semanales los viernes y sábados&lt;/li&gt;
&lt;li&gt;Caída de vistas diarias en febrero que pica de nuevo en marzo&lt;/li&gt;
&lt;li&gt;Caída de vistas diarias a mediados de abril&lt;/li&gt;
&lt;li&gt;Las vistas diarias aumentaban a lo largo del verano, y decrecían después de agosto, y otra vez en deciembre.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Cuando vi este gráfico por la primera vez, presumí que la caída de vistas en febrero era por la Cuaresma. Pero cuando marqué los días festivos, no había correlación.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/vpd-holiday.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Todavía, este gráfico muestra coincidencias con otros días festivos. Las vistas diarias bajaron y se establecieron durante la Semana Santa (9 - 15 de abril). El videoclip también fue popular en la Nochebuena y la Nochevieja, aunque no habían tantas vistas el resto de diciembre.&lt;/p&gt;
&lt;p&gt;El aumento de la popularidad del videoclip puede seguir cuando la canción era popular en otros lugares. En México, la canción superó Los 40 el 11 de febrero. En EEUU, llegó a número 1 en Hot Latin Songs de Billboard para la semana de 18 de febrero. &lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/vpd-charts.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Sospeché que la canción se habría levantado cuando el remix de Justin Bieber salió el 16 de abril. Las vistas sí aumentaron después de esa fecha, pero no se puede identificar si es por Justin Bieber o por la Pascua.&lt;/p&gt;
&lt;p&gt;El 15 de mayo, la canción llegó a número 1 en Billboard's Hot 100, donde se quedaría por muchas semanas a lo largo del verano. Otra vez, no se puede ver un aumento significativo en esa fecha. &lt;/p&gt;
&lt;p&gt;Después de que superó 3 mil millones de vistas, un hito sin precedentes, la popularidad del videoclip disminuyó. Quizás los jóvenes ya no tenían tiempo para reproducirlo. Aun cuando la canción ganó 4 premios de Latin Grammys en noviembre, las vistas diarias seguían la típica tendencia.&lt;/p&gt;
&lt;p&gt;Me interesa explicar los días que no siguen la tendencia. Para identificar anomalías, hice este gráfico que muestra la diferencia de vistas del día anterior.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/change-vpd.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;El gráfico también muestra que las vistas diarias aumentan los viernes y sábados, y bajan los domingos y lunes. Hay algunas excepciones notables. El único sábado cuando las vistas disminuyó era el 1 de febrero. El único viernes cuando las vistas disminuyó era el 14 de abril- Viernes Santo. &lt;/p&gt;
&lt;p&gt;También hay algunos picos peculiares. Primero, el miércoles 8 de marzo, 2017. No puedo encontrar nada para explicar por qué había tantas vistas ese miércoles. Presiento que el algoritmo de sugerencias de YouTube escondió el vídeo desde 1 de febrero hasta 8 de marzo. Así que la gente no podía encontrar el vídeo por sus sugerencias.&lt;/p&gt;
&lt;p&gt;Los otros picos considerables son de los domingos de la Nochebuena y la Nochevieja. No es típico tener más vistas el domingo que el sábado. &lt;/p&gt;
&lt;h1&gt;Predecir las vistas&lt;/h1&gt;
&lt;p&gt;Ahora intento predecir el número de vistas en el futuro. Un modelo de efectos principales con factores &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; y &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; tiene la forma  &lt;/p&gt;
&lt;div class="math"&gt;$$
y_{ijk} = \mu +\alpha_i+\beta_j+e_{ijk}
$$&lt;/div&gt;
&lt;p&gt;donde &lt;span class="math"&gt;\(\mu\)&lt;/span&gt; es el promedio general, &lt;span class="math"&gt;\(\alpha_i\)&lt;/span&gt; y &lt;span class="math"&gt;\(\beta_j\)&lt;/span&gt; son los efectos principales de los factores, y &lt;span class="math"&gt;\(e_{ijk}\)&lt;/span&gt; es el error. Para las vistas del videoclip, presumo que el número de vistas en un día particular depende de solo el mes y el día de la semana. &lt;/p&gt;
&lt;div class="math"&gt;$$
\text{views}_{ijk} = \mu +\text{month}_i+\text{wday}_j+e_{ijk}
$$&lt;/div&gt;
&lt;p&gt;
Es fácil hacer esto en R.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;view_mod &lt;span class="o"&gt;=&lt;/span&gt; lm&lt;span class="p"&gt;(&lt;/span&gt;views &lt;span class="o"&gt;~&lt;/span&gt; &lt;span class="kp"&gt;factor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;month&lt;span class="p"&gt;,&lt;/span&gt; ordered &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;FALSE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; wday&lt;span class="p"&gt;,&lt;/span&gt; data &lt;span class="o"&gt;=&lt;/span&gt; despacito_df&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kp"&gt;summary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;view_mod&lt;span class="p"&gt;)[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;coefficients&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##                                     Estimate Std. Error    t value
## (Intercept)                        6101017.5   368686.2 16.5479942
## factor(month, ordered = FALSE)Feb   504094.8   437943.9  1.1510488
## factor(month, ordered = FALSE)Mar  4354379.6   427075.1 10.1958162
## factor(month, ordered = FALSE)Apr  7317787.7   430508.1 16.9980251
## factor(month, ordered = FALSE)May  9987258.8   426805.1 23.4000478
## factor(month, ordered = FALSE)Jun 11658600.7   430508.3 27.0810138
## factor(month, ordered = FALSE)Jul 13765615.4   426940.1 32.2425001
## factor(month, ordered = FALSE)Aug 11478848.1   426940.1 26.8863215
## factor(month, ordered = FALSE)Sep  5599158.5   430508.3 13.0059252
## factor(month, ordered = FALSE)Oct  2287510.1   426805.1  5.3596133
## factor(month, ordered = FALSE)Nov   704704.9   430508.1  1.6369144
## factor(month, ordered = FALSE)Dec -1384111.2   427075.1 -3.2409078
## wdayTuesday                          74460.1   326885.8  0.2277863
## wdayWednesday                       278608.4   327092.7  0.8517719
## wdayThursday                        659271.2   327196.1  2.0149112
## wdayFriday                         2110548.1   327196.1  6.4504076
## wdaySaturday                       3672752.2   327094.4 11.2284172
## wdaySunday                         1415449.2   326990.9  4.3287110
##                                        Pr(&amp;gt;|t|)
## (Intercept)                        1.009681e-45
## factor(month, ordered = FALSE)Feb  2.505070e-01
## factor(month, ordered = FALSE)Mar  1.614956e-21
## factor(month, ordered = FALSE)Apr  1.548200e-47
## factor(month, ordered = FALSE)May  2.839371e-73
## factor(month, ordered = FALSE)Jun  1.723188e-87
## factor(month, ordered = FALSE)Jul 2.831538e-106
## factor(month, ordered = FALSE)Aug  9.381737e-87
## factor(month, ordered = FALSE)Sep  9.256291e-32
## factor(month, ordered = FALSE)Oct  1.526429e-07
## factor(month, ordered = FALSE)Nov  1.025575e-01
## factor(month, ordered = FALSE)Dec  1.307217e-03
## wdayTuesday                        8.199470e-01
## wdayWednesday                      3.949298e-01
## wdayThursday                       4.468707e-02
## wdayFriday                         3.759610e-10
## wdaySaturday                       3.726519e-25
## wdaySunday                         1.966222e-05
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;El resumen muestra los coeficientes del modelo. El &lt;code&gt;(Intercept)&lt;/code&gt; es la base de referencia a la que los otros coeficientes comparan. Aquí es enero y lunes. Entonces, el coeficiente para febrero se puede interpretar como "504094.8 más vistas en febrero que en enero."&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Mi interpretación puede ser equivocada. Traté de verificar los valores con otros métodos, y no podía replicar los resultos. Además, me habría gustado que el resumen reflejara la forma del modelo arriba, (i.e. sin el intercepto). Usando &lt;code&gt;- 1&lt;/code&gt; quita el intercepto y añade enero, pero no incluye lunes. Si alguién tenga sugerencias, por favor contáctame.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A pesar de la interpretación, el modelo predice bien las vistas. Mira los valores ajustados (rojo) y los valores reales (negro).&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/predict.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Ahora si queremos predecir cuando el vídeo llegará 5, 6, o 7 mil millones de vistas, creamos una hoja de datos que tiene el mes y el día de fechas en el futuro. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_days &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;seq.Date&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;ymd&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;2018-01-13&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; ymd&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;2020-01-01&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; by &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;day&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
future_df &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;data.frame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;month &lt;span class="o"&gt;=&lt;/span&gt; month&lt;span class="p"&gt;(&lt;/span&gt;future_days&lt;span class="p"&gt;,&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                       wday &lt;span class="o"&gt;=&lt;/span&gt; wday&lt;span class="p"&gt;(&lt;/span&gt;future_days&lt;span class="p"&gt;,&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; abbr &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;FALSE&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Luego, predecimos el número de vistas en cada uno de estas fechas. La suposición principal es que el vídeo seguirá el mismo pauta en el futuro.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_views &lt;span class="o"&gt;=&lt;/span&gt; predict&lt;span class="p"&gt;(&lt;/span&gt;view_mod&lt;span class="p"&gt;,&lt;/span&gt; newdata &lt;span class="o"&gt;=&lt;/span&gt; future_df&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Usamos la función de la suma cumulativa para ver las vistas acumulativas en cada fecha. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_total &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;cumsum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_views&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;cumviews&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="c1"&gt;# Adding current total&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Por fin vemos las fechas cuando los hitos ocurrirán.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_milestones &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;t_5b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;5e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_6b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;6e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_7b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;7e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_8b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;8e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_9b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;9e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_10b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;1e10&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="kp"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_milestones&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##         t_5b         t_6b         t_7b         t_8b         t_9b 
## &amp;quot;2018-02-24&amp;quot; &amp;quot;2018-05-10&amp;quot; &amp;quot;2018-07-04&amp;quot; &amp;quot;2018-08-23&amp;quot; &amp;quot;2018-11-19&amp;quot; 
##        t_10b 
## &amp;quot;2019-03-25&amp;quot;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Según este modelo, el videoclip de &lt;em&gt;Despacito&lt;/em&gt; llegará a 5 mil millones de vistas el 24 de febrero, 2018 y 10 mil millones el 25 de marzo, 2019. No creo que este modelo sirva muy bien después de unos meses. Los datos que uso son del primer año de esta canción, cuando era nueva y su popularidad estaba en su máximo. Ya ha completado su dominación en las listas musicales alrededor del mundo. El año 2018 tendrá canciones y videoclips más populares, y este vídeo será una reliquia del pasado. Todavía yo volveré en marzo para ver que precisas eran mis predicciones.&lt;/p&gt;
&lt;h1&gt;Referencias&lt;/h1&gt;
&lt;p&gt;https://www.youtube.com/watch?v=kJQP7kiw5Fk&lt;/p&gt;
&lt;p&gt;https://es.wikipedia.org/wiki/Despacito&lt;/p&gt;
&lt;p&gt;https://www.billboard.com/articles/columns/chart-beat/7793159/luis-fonsi-daddy-yankee-despacito-justin-bieber-number-one&lt;/p&gt;
&lt;p&gt;http://los40.com.mx/lista40/2017/6&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category><category term="YouTube"></category><category term="visualization"></category></entry><entry><title>One Year of Despacito</title><link href="http://maazinansari.com/posts/despacito-1" rel="alternate"></link><published>2018-01-13T00:00:00-06:00</published><updated>2018-01-13T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-01-13:/posts/despacito-1</id><summary type="html">&lt;p&gt;A quick and dirty analysis of music video views&lt;/p&gt;</summary><content type="html">&lt;p&gt;Luis Fonsi's &lt;em&gt;Despacito&lt;/em&gt; ft. Daddy Yankee was the song of 2017. Released in early January, the song became an instant hit in Latin America. After Justin Bieber got involved, it dominated charts around the world.&lt;/p&gt;
&lt;p&gt;The music video for the original Spanish-language version was published on YouTube on January 12, 2017, one year ago today. In just 97 days, the video received one billion views. Views kept coming in, and by August 4- just 7 months after its release- the video became the first video in YouTube history to break 3 billion. &lt;/p&gt;
&lt;p&gt;In this post I will analyze how the music video grew so fast. I will identify weekly trends and moments where the view count grew rapidly. Currently, I don't have much experience with time series, so this analysis will be mostly visual. &lt;/p&gt;
&lt;p&gt;Data, scripts, and additional plots are available on &lt;a href="https://github.com/maazinansari/maazinansari/tree/master/content/R/despacito"&gt;my GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Getting the data&lt;/h1&gt;
&lt;p&gt;YouTube provides video statistics for some of its videos. I'm not sure what determines whether a video has statistics enabled, but it seems most music videos have them. Here's what the daily view graph looks like for Despacito:&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/yt-viz.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;We can get the data we need directly from the HTML used to create this table.&lt;/p&gt;
&lt;p&gt;It's important to note video statistics are only available in the previous YouTube format. For some reason, YouTube removed the video statistics in their new layout.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/oldtube.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;img src="../../static/despacito/newtube.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Once you're at the page and you have opened the video statistics, right-click somewhere around the chart and inspect element. You won't be able to right-click the actual graphic itself, but the axis labels should work. Look for &lt;code&gt;stats-chart-gviz&lt;/code&gt; in the HTML. Click the arrows until you find the &lt;code&gt;&amp;lt;table&amp;gt;&lt;/code&gt; tag. Right-click and select Copy &amp;gt; Copy element and paste it into a text editor and save it as an .html file.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/html-elements.png" title="center" alt="center" width="75%" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h1&gt;Cleaning the data&lt;/h1&gt;
&lt;p&gt;Now our data is saved as an HTML table. We need to get the dates and values from it to make our own graphs. We'll need the &lt;code&gt;XML&lt;/code&gt; package for this. Specifically, we use the &lt;code&gt;readHTMLTable()&lt;/code&gt; function to read the data as a dataframe. Then, we create new &lt;code&gt;date&lt;/code&gt; and &lt;code&gt;views&lt;/code&gt; columns that contain the date and number of views in appropriate formats. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# Cleaning ----&lt;/span&gt;
&lt;span class="c1"&gt;# This script only works for data taken from the English language YouTube site.&lt;/span&gt;
despacito_table &lt;span class="o"&gt;=&lt;/span&gt; readHTMLTable&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;despacito_table.html&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
despacito_df &lt;span class="o"&gt;=&lt;/span&gt; despacito_table&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;strptime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;as.character&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;%b %d, %Y&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;as.Date&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;gsub&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;,&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;as.numeric&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Let's add more columns to make analysis and plotting easier later on.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# Cumulative views&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;cumviews&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;cumsum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;

&lt;span class="c1"&gt;# Change in views from previous day&lt;/span&gt;
change &lt;span class="o"&gt;=&lt;/span&gt; despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;views&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;change&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; change

&lt;span class="c1"&gt;# Add year, month, day of week&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;year&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; year&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;month&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; month&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;wday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;factor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;weekdays&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]),&lt;/span&gt;
                           levels&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Monday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Tuesday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Wednesday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Thursday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Friday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Saturday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Sunday&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;h1&gt;Analysis&lt;/h1&gt;
&lt;p&gt;Now that we have cleaned data, we can make some plots.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/views-per-day.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;img src="../../static/despacito/total.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;These plots are the same as the ones YouTube generates, with certain view milestones marked. From this we can see some interesting patterns:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Weekly spikes on Fridays and Saturdays&lt;/li&gt;
&lt;li&gt;Drop in views per day in February that spikes again in March&lt;/li&gt;
&lt;li&gt;Drop in views per day in mid-April&lt;/li&gt;
&lt;li&gt;Views per day continued growing through the summer, then dropped after August, then again in December.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When I first saw this plot, I assumed the drop in views in February was due to people limiting music during Lent. But when I marked major holidays on the plot, the correlation wasn't there.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/vpd-holiday.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Still, this plot shows coincidences with other holidays. Views dropped and steadied during Holy Week (April 9 - 15). The video was also popular on Christmas Eve and New Year's Eve, though not so much the rest of December.&lt;/p&gt;
&lt;p&gt;The rise in the video's popularity could follow when the song was popular elsewhere. The song first topped Mexico's Los 40 on February 11. In the US, the song sat at number 1 on Billboard's Hot Latin Songs for the week of February 18. &lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/vpd-charts.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;I suspected the song to have received a boost when the Justin Bieber remix came out on April 16. Views did spike after that date, but it's hard to tell if it's from the remix, or from the end of Lent.&lt;/p&gt;
&lt;p&gt;On May 15, the song hit number 1 on Billboard's Hot 100, where it would sit for several weeks through the summer. Again, there isn't a significant increase in views around that time. &lt;/p&gt;
&lt;p&gt;After the video hit an unprecedented 3 billion views, its popularity dropped. Perhaps as kids were going back to school, there were fewer people playing it than in the summer. Even when the song won 4 awards at the Latin Grammys in November, daily views followed the same pattern.&lt;/p&gt;
&lt;p&gt;I'm interested in explaining the days that don't follow the trend. To better identify anomalies, I made a bar plot that colors the days of the week.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/change-vpd.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;This plot better shows that daily views increase on Friday and Saturday, then drop Sunday and Monday. There are some notable exceptions. The only Saturday where views dropped was February 1. The only Friday where views dropped was April 14- Good Friday. &lt;/p&gt;
&lt;p&gt;There are also some unusual days where views spiked. First, there was a spike on Wednesday March 8, 2017. I cannot find anything that could explain why views spiked so much on that Wednesday. My hunch is that YouTube's suggestion algorithm effectively hid the video from February 1 to March 8, so people did not find it through their suggested videos.&lt;/p&gt;
&lt;p&gt;The other major spikes were the Sundays of Christmas Eve and New Year's Eve. &lt;/p&gt;
&lt;h1&gt;Predicting future views&lt;/h1&gt;
&lt;p&gt;Now for a crude attempt at predicting views in the future. A main effects model with factors &lt;span class="math"&gt;\(\alpha\)&lt;/span&gt; and &lt;span class="math"&gt;\(\beta\)&lt;/span&gt; has the form  &lt;/p&gt;
&lt;div class="math"&gt;$$
y_{ijk} = \mu +\alpha_i+\beta_j+e_{ijk}
$$&lt;/div&gt;
&lt;p&gt;where &lt;span class="math"&gt;\(\mu\)&lt;/span&gt; is the overall mean, &lt;span class="math"&gt;\(\alpha_i\)&lt;/span&gt; and &lt;span class="math"&gt;\(\beta_j\)&lt;/span&gt; are the main effects of the factors, and &lt;span class="math"&gt;\(e_{ijk}\)&lt;/span&gt; is the error. For the music video views, I am assuming the number of views on a certain day depends on only the month and day of the week. &lt;/p&gt;
&lt;div class="math"&gt;$$
\text{views}_{ijk} = \mu +\text{month}_i+\text{wday}_j+e_{ijk}
$$&lt;/div&gt;
&lt;p&gt;
This is easy to do in R.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;view_mod &lt;span class="o"&gt;=&lt;/span&gt; lm&lt;span class="p"&gt;(&lt;/span&gt;views &lt;span class="o"&gt;~&lt;/span&gt; &lt;span class="kp"&gt;factor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;month&lt;span class="p"&gt;,&lt;/span&gt; ordered &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;FALSE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; wday&lt;span class="p"&gt;,&lt;/span&gt; data &lt;span class="o"&gt;=&lt;/span&gt; despacito_df&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kp"&gt;summary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;view_mod&lt;span class="p"&gt;)[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;coefficients&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##                                     Estimate Std. Error    t value
## (Intercept)                        6101017.5   368686.2 16.5479942
## factor(month, ordered = FALSE)Feb   504094.8   437943.9  1.1510488
## factor(month, ordered = FALSE)Mar  4354379.6   427075.1 10.1958162
## factor(month, ordered = FALSE)Apr  7317787.7   430508.1 16.9980251
## factor(month, ordered = FALSE)May  9987258.8   426805.1 23.4000478
## factor(month, ordered = FALSE)Jun 11658600.7   430508.3 27.0810138
## factor(month, ordered = FALSE)Jul 13765615.4   426940.1 32.2425001
## factor(month, ordered = FALSE)Aug 11478848.1   426940.1 26.8863215
## factor(month, ordered = FALSE)Sep  5599158.5   430508.3 13.0059252
## factor(month, ordered = FALSE)Oct  2287510.1   426805.1  5.3596133
## factor(month, ordered = FALSE)Nov   704704.9   430508.1  1.6369144
## factor(month, ordered = FALSE)Dec -1384111.2   427075.1 -3.2409078
## wdayTuesday                          74460.1   326885.8  0.2277863
## wdayWednesday                       278608.4   327092.7  0.8517719
## wdayThursday                        659271.2   327196.1  2.0149112
## wdayFriday                         2110548.1   327196.1  6.4504076
## wdaySaturday                       3672752.2   327094.4 11.2284172
## wdaySunday                         1415449.2   326990.9  4.3287110
##                                        Pr(&amp;gt;|t|)
## (Intercept)                        1.009681e-45
## factor(month, ordered = FALSE)Feb  2.505070e-01
## factor(month, ordered = FALSE)Mar  1.614956e-21
## factor(month, ordered = FALSE)Apr  1.548200e-47
## factor(month, ordered = FALSE)May  2.839371e-73
## factor(month, ordered = FALSE)Jun  1.723188e-87
## factor(month, ordered = FALSE)Jul 2.831538e-106
## factor(month, ordered = FALSE)Aug  9.381737e-87
## factor(month, ordered = FALSE)Sep  9.256291e-32
## factor(month, ordered = FALSE)Oct  1.526429e-07
## factor(month, ordered = FALSE)Nov  1.025575e-01
## factor(month, ordered = FALSE)Dec  1.307217e-03
## wdayTuesday                        8.199470e-01
## wdayWednesday                      3.949298e-01
## wdayThursday                       4.468707e-02
## wdayFriday                         3.759610e-10
## wdaySaturday                       3.726519e-25
## wdaySunday                         1.966222e-05
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The summary shows the coefficients of the model. The &lt;code&gt;(Intercept)&lt;/code&gt; is the baseline to which all other coefficients are compared. Here the baseline is January and Monday. So, the estimated coefficient for February can be interpreted as "504094.8 more views in February than in January."&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Sidenote: My interpretation here might be wrong. I tried verifying the values with other methods, and couldn't replicate the results. Also, I would've liked for the summary to reflect the form of the main effects model above, (i.e. without the intercept). Using &lt;code&gt;- 1&lt;/code&gt; gets rid of the intercept and includes January, but not Monday. If anyone has any suggestions for me, please feel free to reach out.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Regardless of its interpretation, the model does a decent job at predicting. Take a look at the fitted values (in red) compared to the true values.&lt;/p&gt;
&lt;p&gt;&lt;img src="../../static/despacito/predict.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;Now if we want to predict when the video will reach 5, 6, or 7 billion views, we'll first need to create a data frame of predictors that contains the month and day of future dates. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_days &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;seq.Date&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;ymd&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;2018-01-13&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; ymd&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;2020-01-01&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; by &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;day&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
future_df &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;data.frame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;month &lt;span class="o"&gt;=&lt;/span&gt; month&lt;span class="p"&gt;(&lt;/span&gt;future_days&lt;span class="p"&gt;,&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                       wday &lt;span class="o"&gt;=&lt;/span&gt; wday&lt;span class="p"&gt;(&lt;/span&gt;future_days&lt;span class="p"&gt;,&lt;/span&gt; label &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; abbr &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;FALSE&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Next, we predict the number of views on each of those days, assuming views follow the same pattern in the future as in 2017. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_views &lt;span class="o"&gt;=&lt;/span&gt; predict&lt;span class="p"&gt;(&lt;/span&gt;view_mod&lt;span class="p"&gt;,&lt;/span&gt; newdata &lt;span class="o"&gt;=&lt;/span&gt; future_df&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Then, we'll take the cumulative sum to see the total views on each date. &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_total &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;cumsum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_views&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; despacito_df&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;despacito_df&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;cumviews&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="c1"&gt;# Adding current total&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Finally, we can see the dates where certain view milestones will occur.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;future_milestones &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;c&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;t_5b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;5e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_6b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;6e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_7b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;7e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_8b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;8e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_9b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;9e9&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                      t_10b &lt;span class="o"&gt;=&lt;/span&gt; future_days&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kp"&gt;which&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_total &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="m"&gt;1e10&lt;/span&gt;&lt;span class="p"&gt;)][&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="kp"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;future_milestones&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;##         t_5b         t_6b         t_7b         t_8b         t_9b 
## &amp;quot;2018-02-24&amp;quot; &amp;quot;2018-05-10&amp;quot; &amp;quot;2018-07-04&amp;quot; &amp;quot;2018-08-23&amp;quot; &amp;quot;2018-11-19&amp;quot; 
##        t_10b 
## &amp;quot;2019-03-25&amp;quot;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;With this model, the music video for &lt;em&gt;Despacito&lt;/em&gt; will reach 5 billion views on February 24, 2018 and 10 billion on March 25, 2019. I don't expect this model to perform very well beyond a few months. The data I used was from the first year of the song, when it was new and its popularity was at its peak. It has already completed its reign over charts around the world. 2018 may have hotter songs and music videos, and this video will be a relic of the past. Still, I'll be back in March to check how well these predictions held up. &lt;/p&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;p&gt;https://www.youtube.com/watch?v=kJQP7kiw5Fk&lt;/p&gt;
&lt;p&gt;https://en.wikipedia.org/wiki/Despacito&lt;/p&gt;
&lt;p&gt;https://www.billboard.com/articles/columns/chart-beat/7793159/luis-fonsi-daddy-yankee-despacito-justin-bieber-number-one&lt;/p&gt;
&lt;p&gt;http://los40.com.mx/lista40/2017/6&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category><category term="YouTube"></category><category term="visualization"></category></entry><entry><title>100-Year Flood Part 1</title><link href="http://maazinansari.com/posts/100-yr-flood-1" rel="alternate"></link><published>2018-01-12T00:00:00-06:00</published><updated>2018-01-12T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-01-12:/posts/100-yr-flood-1</id><summary type="html">&lt;p&gt;A demonstration of parameter estimation of a lognormal distribution&lt;/p&gt;</summary><content type="html">&lt;p&gt;In this two-part post, I play around with some data in R to show the statistics behind parameter estimation and the 100-year flood. This is mostly me following along with posts from other blogs to get familiar with R, RMarkdown, and blogging. &lt;/p&gt;
&lt;p&gt;In this first part, I'll show how the hundred year flood is calculated from data. In Part 2, I'll go into more detail on the 100-year flood, do some simulations, and verify our solution in Part 1.&lt;/p&gt;
&lt;h1&gt;Parameter Estimation&lt;/h1&gt;
&lt;p&gt;The data I use here comes from Problem 6&lt;sup id="fnref-2"&gt;&lt;a class="footnote-ref" href="#fn-2"&gt;2&lt;/a&gt;&lt;/sup&gt; in &lt;/p&gt;
&lt;p&gt;Ross, Sheldon M. “Chapter 7: Parameter Estimation.” &lt;em&gt;Introduction to Probability and Statistics for Engineers and Scientists&lt;/em&gt;, 5th ed., Elsevier, AP, 2014, pp. 285–286.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;River floods are often measured by their discharges &lt;span class="math"&gt;\((\text{ft}^3/\text{s})\)&lt;/span&gt;
The value &lt;span class="math"&gt;\(v\)&lt;/span&gt; is said to be the value of a 100-year flood if &lt;span class="math"&gt;\(P(D \geq v) = 0.01\)&lt;/span&gt;
where &lt;span class="math"&gt;\(D\)&lt;/span&gt; is the discharge of the largest flood in a randomly selected year.  &lt;/p&gt;
&lt;p&gt;The table below gives the flood discharges of the largest floods of the Blackstone River in Woonsocket, RI, in each year from 1929 to 1965.  &lt;/p&gt;
&lt;p&gt;Assuming that these discharges follow a log-normal distribution, estimate the value of a 100-year flood.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="center"&gt;year&lt;/th&gt;
&lt;th align="center"&gt;discharge&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1929&lt;/td&gt;
&lt;td align="center"&gt;4750&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1930&lt;/td&gt;
&lt;td align="center"&gt;1970&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1931&lt;/td&gt;
&lt;td align="center"&gt;8220&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1932&lt;/td&gt;
&lt;td align="center"&gt;4530&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1933&lt;/td&gt;
&lt;td align="center"&gt;5780&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1934&lt;/td&gt;
&lt;td align="center"&gt;6560&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1935&lt;/td&gt;
&lt;td align="center"&gt;7500&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1936&lt;/td&gt;
&lt;td align="center"&gt;15000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1937&lt;/td&gt;
&lt;td align="center"&gt;6340&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1938&lt;/td&gt;
&lt;td align="center"&gt;15100&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1939&lt;/td&gt;
&lt;td align="center"&gt;3840&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1940&lt;/td&gt;
&lt;td align="center"&gt;5860&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1941&lt;/td&gt;
&lt;td align="center"&gt;4480&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1942&lt;/td&gt;
&lt;td align="center"&gt;5330&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1943&lt;/td&gt;
&lt;td align="center"&gt;5310&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1944&lt;/td&gt;
&lt;td align="center"&gt;3830&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1945&lt;/td&gt;
&lt;td align="center"&gt;3410&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1946&lt;/td&gt;
&lt;td align="center"&gt;3830&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1947&lt;/td&gt;
&lt;td align="center"&gt;3150&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1948&lt;/td&gt;
&lt;td align="center"&gt;5810&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1949&lt;/td&gt;
&lt;td align="center"&gt;2030&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1950&lt;/td&gt;
&lt;td align="center"&gt;3620&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1951&lt;/td&gt;
&lt;td align="center"&gt;4920&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1952&lt;/td&gt;
&lt;td align="center"&gt;4090&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1953&lt;/td&gt;
&lt;td align="center"&gt;5570&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1954&lt;/td&gt;
&lt;td align="center"&gt;9400&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1955&lt;/td&gt;
&lt;td align="center"&gt;32900&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1956&lt;/td&gt;
&lt;td align="center"&gt;8710&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1957&lt;/td&gt;
&lt;td align="center"&gt;3850&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1958&lt;/td&gt;
&lt;td align="center"&gt;4970&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1959&lt;/td&gt;
&lt;td align="center"&gt;5398&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1960&lt;/td&gt;
&lt;td align="center"&gt;4780&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1961&lt;/td&gt;
&lt;td align="center"&gt;4020&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1962&lt;/td&gt;
&lt;td align="center"&gt;5790&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1963&lt;/td&gt;
&lt;td align="center"&gt;4510&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1964&lt;/td&gt;
&lt;td align="center"&gt;5520&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;1965&lt;/td&gt;
&lt;td align="center"&gt;5300&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The plot below displays the above table as a graph. The average discharge of the largest flood during this period is around 6,000 &lt;span class="math"&gt;\(\text{ft}^3/\text{s}\)&lt;/span&gt;. There was an unusually large flood in 1955, with well over 30,000 &lt;span class="math"&gt;\(\text{ft}^3/\text{s}\)&lt;/span&gt; of discharge.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;plot&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;,&lt;/span&gt; type &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;h&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; lwd &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     main &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;Largest floods of the Blackstone River&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="/static/HundredYrFlood1/time-plot-1-1.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;h2&gt;Distribution of discharges&lt;/h2&gt;
&lt;p&gt;The problem tells us to assume discharge follows a log-normal distribution. So, &lt;span class="math"&gt;\(D \sim \text{Lognormal}(\mu, \sigma)\)&lt;/span&gt;. Two notable properties of the log-normal distribution are that it takes positive values and it is positively skewed. Looking at the histogram of discharges, we can see both are true: discharges cannot be less than 0 and high-discharge floods are much less frequent than low-discharge floods.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;hist&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; nclass &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;25&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; freq &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;TRUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; xlab &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; main &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img src="/static/HundredYrFlood1/hist-1-1.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;The next step is to determine which log-normal distribution this data comes from. In other words, what are the parameters for this distribution?&lt;/p&gt;
&lt;h2&gt;Log-normal distribution&lt;/h2&gt;
&lt;div class="math"&gt;$$f(x) = \frac{1}{x\sigma\sqrt{2π}} \exp\Big(-\frac{(\ln x - \mu)^2}{2 \sigma^2}\Big)$$&lt;/div&gt;
&lt;p&gt;The log-normal distribution is similar to the normal distribution in that it has two parameters, &lt;span class="math"&gt;\(\mu\)&lt;/span&gt; and &lt;span class="math"&gt;\(\sigma\)&lt;/span&gt;. We need to estimate both.&lt;/p&gt;
&lt;p&gt;The following sections show how to estimate the parameters for the log-normal distribution, using four different methods I found in a paper on log-normal parameter estimation&lt;sup id="fnref-1"&gt;&lt;a class="footnote-ref" href="#fn-1"&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;h3&gt;Maximum Likelihood Estimates&lt;/h3&gt;
&lt;div class="math"&gt;$$
\hat{\mu}=\frac{\sum \ln x_i}{n} = \overline{\ln x_i}
$$&lt;/div&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;mu_hat &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="math"&gt;$$
\hat{\sigma}^2 = \frac{\sum_i^n (\ln x_i - \hat{\mu})^2}{n}
$$&lt;/div&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;sigma_hat &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; mu_hat&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;^&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; mean &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;sqrt&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;h3&gt;Method of Moments Estimates&lt;/h3&gt;
&lt;div class="math"&gt;$$
\tilde{\sigma}^2= \ln{\sum_{i=1}^nx_i^2} - 2\ln{\sum_{i=1}^nx_i}+\ln(n)
$$&lt;/div&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;sigma_tilde &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;&lt;span class="o"&gt;^&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; sum &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;
    &lt;span class="m"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; sum &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
    &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;)))&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt;
    &lt;span class="kp"&gt;sqrt&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="math"&gt;$$
\tilde{\mu}= {\ln \sum_{i=1}^n x_i}-\ln(n)-\frac{\tilde{\sigma}^2}{2}
$$&lt;/div&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;mu_tilde &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; sum &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;
            &lt;span class="kp"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kp"&gt;nrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; 
            &lt;span class="p"&gt;(&lt;/span&gt;sigma_tilde&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;^&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="m"&gt;2&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;h3&gt;Serfling Robust Estimates and Finney Efficient Estimates&lt;/h3&gt;
&lt;p&gt;The next two methods are a little more complex.&lt;/p&gt;
&lt;p&gt;The Serfling method computes a sample statistic for all &lt;span class="math"&gt;\(n\choose k\)&lt;/span&gt; permutations of the data, then selects the median as the estimate. &lt;/p&gt;
&lt;p&gt;I made slight modifications to the algorithm for the sake of computation speed. First, I only use 10,000 permutations. Serfling and Ginos limit the number of permutations to 10^7^, but I found even that was too high for R. Second, I did not intentionally use unique permutations. Instead I drew random samples of &lt;span class="math"&gt;\(k=9\)&lt;/span&gt; from the data. I didn't check if all 10,000 were unique. Maybe later I'll make a post investigating how much accuracy my method compromises for speed.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;source&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;serfling.R&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

serfling_estimates &lt;span class="o"&gt;=&lt;/span&gt; serfling_estimate_1&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
mu_hat_serf &lt;span class="o"&gt;=&lt;/span&gt; serfling_estimates&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
sigma_hat_serf &lt;span class="o"&gt;=&lt;/span&gt; serfling_estimates&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The Finney method uses adjusted versions of the sample mean and variance to estimate &lt;span class="math"&gt;\(\mu\)&lt;/span&gt; and &lt;span class="math"&gt;\(\sigma\)&lt;/span&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;source&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;finney.R&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

finney_estimates &lt;span class="o"&gt;=&lt;/span&gt; finney_estimate_1&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;discharge&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
mu_hat_finney &lt;span class="o"&gt;=&lt;/span&gt; finney_estimates&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
sigma_hat_finney &lt;span class="o"&gt;=&lt;/span&gt; finney_estimates&lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;h2&gt;Estimated distributions&lt;/h2&gt;
&lt;p&gt;Since we now have parameters, we have distributions. We can plot the four probability density functions with the histogram to see how well they fit with the data.&lt;/p&gt;
&lt;p&gt;&lt;img alt="center" src="/static/HundredYrFlood1/hist-2-1.png"&gt;&lt;/p&gt;
&lt;p&gt;Note that the Finney efficient estimates are very similar to the maximum likelihood estimates. &lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="left"&gt;&lt;/th&gt;
&lt;th align="right"&gt;Mu&lt;/th&gt;
&lt;th align="right"&gt;Sigma&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="left"&gt;MLE&lt;/td&gt;
&lt;td align="right"&gt;8.594057&lt;/td&gt;
&lt;td align="right"&gt;0.5116531&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;MOM&lt;/td&gt;
&lt;td align="right"&gt;8.593508&lt;/td&gt;
&lt;td align="right"&gt;0.5118573&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;Serfling&lt;/td&gt;
&lt;td align="right"&gt;8.505484&lt;/td&gt;
&lt;td align="right"&gt;0.7142709&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;Finney&lt;/td&gt;
&lt;td align="right"&gt;8.586239&lt;/td&gt;
&lt;td align="right"&gt;0.4270907&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Now we can determine the value &lt;span class="math"&gt;\(v\)&lt;/span&gt; for which &lt;span class="math"&gt;\(P(D \geq v) = 0.01\)&lt;/span&gt; or equivalently &lt;span class="math"&gt;\(P(D &amp;lt;  v) = 0.99\)&lt;/span&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;v_mle &lt;span class="o"&gt;=&lt;/span&gt; qlnorm&lt;span class="p"&gt;(&lt;/span&gt;p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.99&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; meanlog &lt;span class="o"&gt;=&lt;/span&gt; mu_hat&lt;span class="p"&gt;,&lt;/span&gt; sdlog &lt;span class="o"&gt;=&lt;/span&gt; sigma_hat&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;v_mom &lt;span class="o"&gt;=&lt;/span&gt; qlnorm&lt;span class="p"&gt;(&lt;/span&gt;p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.99&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; meanlog &lt;span class="o"&gt;=&lt;/span&gt; mu_tilde&lt;span class="p"&gt;,&lt;/span&gt; sdlog &lt;span class="o"&gt;=&lt;/span&gt; sigma_tilde&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;v_serf &lt;span class="o"&gt;=&lt;/span&gt; qlnorm&lt;span class="p"&gt;(&lt;/span&gt;p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.99&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; meanlog &lt;span class="o"&gt;=&lt;/span&gt; mu_hat_serf&lt;span class="p"&gt;,&lt;/span&gt; sdlog &lt;span class="o"&gt;=&lt;/span&gt; sigma_tilde&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;v_finney &lt;span class="o"&gt;=&lt;/span&gt; qlnorm&lt;span class="p"&gt;(&lt;/span&gt;p &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.99&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; meanlog &lt;span class="o"&gt;=&lt;/span&gt; mu_hat_finney&lt;span class="p"&gt;,&lt;/span&gt; sdlog &lt;span class="o"&gt;=&lt;/span&gt; sigma_hat_finney&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="left"&gt;&lt;/th&gt;
&lt;th align="right"&gt;v&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="left"&gt;MLE&lt;/td&gt;
&lt;td align="right"&gt;17753.54&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;MOM&lt;/td&gt;
&lt;td align="right"&gt;26033.18&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;Serfling&lt;/td&gt;
&lt;td align="right"&gt;28222.70&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="left"&gt;Finney&lt;/td&gt;
&lt;td align="right"&gt;17752.23&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;From the data, we see that in only one year, 1955, was the value exceeded.&lt;/p&gt;
&lt;p&gt;&lt;img src="/static/HundredYrFlood1/lnorm-plots-1.png" title="center" alt="center" style="display: block; margin: auto;" /&gt;&lt;/p&gt;
&lt;p&gt;In the next post, I'll look at how likely this is: to have one such flood in a 37-year period.&lt;/p&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div class="footnote"&gt;
&lt;hr&gt;
&lt;ol&gt;
&lt;li id="fn-1"&gt;
&lt;p&gt;Ginos, Brenda Faith, "Parameter Estimation for the Lognormal Distribution" (2009). &lt;em&gt;All Theses and Dissertations&lt;/em&gt;. 1928. http://scholarsarchive.byu.edu/etd/1928&amp;#160;&lt;a class="footnote-backref" href="#fnref-1" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id="fn-2"&gt;
&lt;p&gt;Ross, Sheldon M. “Chapter 7: Parameter Estimation.” &lt;em&gt;Introduction to Probability and Statistics for Engineers and Scientists&lt;/em&gt;, 5th ed., Elsevier, AP, 2014, pp. 285–286.&amp;#160;&lt;a class="footnote-backref" href="#fnref-2" title="Jump back to footnote 2 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category></entry><entry><title>100-Year Flood Part 2</title><link href="http://maazinansari.com/posts/100-yr-flood-2" rel="alternate"></link><published>2018-01-12T00:00:00-06:00</published><updated>2018-01-12T00:00:00-06:00</updated><author><name>Maazin Ansari</name></author><id>tag:maazinansari.com,2018-01-12:/posts/100-yr-flood-2</id><summary type="html">&lt;p&gt;Simulations of flood counts&lt;/p&gt;</summary><content type="html">&lt;p&gt;In Part 1, I estimated &lt;span class="math"&gt;\(v\)&lt;/span&gt;, the value of the 100-year flood for Blackstone River in Woonsocket, RI. The result using maximum likelihood estimation was 17754 &lt;span class="math"&gt;\(\text{ft}^3/\text{s}\)&lt;/span&gt;. What does that mean, and is it accurate? &lt;/p&gt;
&lt;h1&gt;Background&lt;/h1&gt;
&lt;p&gt;This article is based on &lt;a href="https://tonyladson.wordpress.com/2015/06/07/the-100-year-flood/"&gt;this series of  posts&lt;/a&gt; by Tony Ladson. They are really easy to follow if you don't have much experience with hydrology, probability, or R.&lt;/p&gt;
&lt;p&gt;The value of the 100-year flood was calculated to be 17754. This can be worded in different ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In a single year, there is a 1% chance the discharge of the largest flood will exceed 17754.&lt;/li&gt;
&lt;li&gt;In a 100-year period, the discharge is &lt;em&gt;expected&lt;/em&gt; to be (or exceed) 17754 in one of the years.&lt;/li&gt;
&lt;li&gt;A flood with a discharge of at least 17754 &lt;span class="math"&gt;\(\text{ft}^3/\text{s}\)&lt;/span&gt; is &lt;em&gt;expected&lt;/em&gt; to occur once in a hundred years.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It's not accurate to say the 100-year flood &lt;em&gt;will&lt;/em&gt; occur once every 100 years. The important word is &lt;em&gt;expected&lt;/em&gt;. In a 100-year period, it's possible for zero 100-year floods to occur. It's also possible 37 100-year floods occur.&lt;/p&gt;
&lt;h1&gt;Number of 100-year floods in 37 years&lt;/h1&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;plot&lt;span class="p"&gt;(&lt;/span&gt;floods&lt;span class="p"&gt;,&lt;/span&gt; type &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;h&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; lwd &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
title&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Largest floods&lt;/span&gt;
&lt;span class="s"&gt;      of the Blackstone River&lt;/span&gt;
&lt;span class="s"&gt;      1929-1965&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; cex &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.75&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
abline&lt;span class="p"&gt;(&lt;/span&gt;h &lt;span class="o"&gt;=&lt;/span&gt; v_mle&lt;span class="p"&gt;,&lt;/span&gt; col &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;red&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;img alt="center" src="/static/HundredYrFlood2/time-plot2-1.png"&gt;&lt;/p&gt;
&lt;p&gt;Looking at our original data, the 100-year flood was exceeded once in the 37-year period. How likely is it to have exactly one such flood in a 37-year period? We aren't considering the volume of the flood. That is, we aren't asking how likely it is to have a flood with a discharge of 32900 (the maximum), or what discharge is expected. We are only concerned with how many are expected to occur in a random 37-year period.&lt;/p&gt;
&lt;h2&gt;Expectation&lt;/h2&gt;
&lt;p&gt;The number of 100-year floods &lt;span class="math"&gt;\(X\)&lt;/span&gt; in a &lt;span class="math"&gt;\(n\)&lt;/span&gt;-year period follows a binomial distribution:&lt;/p&gt;
&lt;div class="math"&gt;$$
P(X=k)= {n \choose k}p^k(1-p)^{n-k}
$$&lt;/div&gt;
&lt;p&gt;Here &lt;span class="math"&gt;\(n=37\)&lt;/span&gt; (number of years) and &lt;span class="math"&gt;\(p=0.01\)&lt;/span&gt; (Defined in Part 1 as &lt;span class="math"&gt;\(P(D \geq v)\)&lt;/span&gt;). The number of floods (or number of years where the 100-year flood occurs) &lt;span class="math"&gt;\(k\)&lt;/span&gt; can be any number from 0 to 37, as the flood can occur 0, 1, 2,..., or 37 times in a 37-year period.&lt;/p&gt;
&lt;p&gt;Since &lt;span class="math"&gt;\(n\)&lt;/span&gt; is large (37) and &lt;span class="math"&gt;\(p\)&lt;/span&gt; is small (0.01) we can approximate the binomial distribution with a Poisson distribution.&lt;/p&gt;
&lt;div class="math"&gt;$$
P(X=k) = \frac{e^{-\lambda}\lambda^k}{k!}
$$&lt;/div&gt;
&lt;p&gt;Here the parameter &lt;span class="math"&gt;\(\lambda\)&lt;/span&gt; is approximated with &lt;span class="math"&gt;\(np = 37\times0.01=0.37\)&lt;/span&gt;.
With this approximation, &lt;span class="math"&gt;\(k\)&lt;/span&gt; can be larger than 37, but the probabilities will be so small they're essentially 0.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# P(X = 38)&lt;/span&gt;
dpois&lt;span class="p"&gt;(&lt;/span&gt;x &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;38&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; lambda &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;## [1] 7.03372e-46
&lt;/pre&gt;&lt;/div&gt;


&lt;h2&gt;Simulation&lt;/h2&gt;
&lt;p&gt;Knowing the log-normal distribution, we can simulate 37 years of flooding to see if it matches our result and what we expect.&lt;/p&gt;
&lt;h3&gt;Count simulation&lt;/h3&gt;
&lt;p&gt;We can simulate the number of 100-year floods occuring in a 37-year period by simulating binomial and Poisson processes 1000 times.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kp"&gt;set.seed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;2018&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
N &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1000&lt;/span&gt;
&lt;span class="c1"&gt;# Binomial&lt;/span&gt;
bFloods &lt;span class="o"&gt;=&lt;/span&gt; rbinom&lt;span class="p"&gt;(&lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; N&lt;span class="p"&gt;,&lt;/span&gt; size &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;37&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; prob &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
b_table &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;bFloods&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;N &lt;span class="p"&gt;;&lt;/span&gt; b_table
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;## bFloods
##     0     1     2     3     4 
## 0.697 0.257 0.038 0.007 0.001
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# Poisson&lt;/span&gt;
pFloods &lt;span class="o"&gt;=&lt;/span&gt; rpois&lt;span class="p"&gt;(&lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; N&lt;span class="p"&gt;,&lt;/span&gt; lambda &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;37&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="m"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
p_table &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;pFloods&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;N &lt;span class="p"&gt;;&lt;/span&gt; p_table
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;## pFloods
##     0     1     2     3     4 
## 0.696 0.258 0.039 0.006 0.001
&lt;/pre&gt;&lt;/div&gt;


&lt;h3&gt;Log-normal simulation&lt;/h3&gt;
&lt;p&gt;Another way to simulate the number of 100-year floods is to simulate 37-year periods and count how many floods exceed 17754. This involves an extra step compared to the previous method, and I'm only doing it for demonstration.&lt;/p&gt;
&lt;p&gt;Let's start with a matrix to store simulations of flood discharges. Each column is a simulation (1000 total) and each row will represent a year of flooding (37 total). &lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;N &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;1000&lt;/span&gt;
m &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;replicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; N&lt;span class="p"&gt;,&lt;/span&gt; expr &lt;span class="o"&gt;=&lt;/span&gt; rlnorm&lt;span class="p"&gt;(&lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;37&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; meanlog &lt;span class="o"&gt;=&lt;/span&gt; mu_hat&lt;span class="p"&gt;,&lt;/span&gt; sdlog &lt;span class="o"&gt;=&lt;/span&gt; sigma_hat&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;%&amp;gt;%&lt;/span&gt; &lt;span class="kp"&gt;as.matrix&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Now, let's count how many 100-year floods occured in the 1000 37-year periods. In other words, for each column (simulation), how many rows (years) exceed 17754? Then we'll make a table to see how frequent the counts are.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;sim_counts &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;X &lt;span class="o"&gt;=&lt;/span&gt; m&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;# apply to the matrix m&lt;/span&gt;
                   MARGIN &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="m"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;# for each column...&lt;/span&gt;
                   FUN &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;x&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="kp"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;x &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; v_mle&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;# ...count the number of years &amp;gt; v_mle&lt;/span&gt;
sim_table &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kp"&gt;table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;sim_counts&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;N&lt;span class="p"&gt;;&lt;/span&gt; sim_table
&lt;/pre&gt;&lt;/div&gt;


&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;## sim_counts
##     0     1     2     3     4 
## 0.677 0.261 0.050 0.011 0.001
&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The following graph compares the expected probabilities and the simulated probabilities. The red and blue bars show the expected and simulated counts, respectively. The yellow bars show the counts using simulated floods. &lt;/p&gt;
&lt;p&gt;&lt;img alt="center" src="/static/HundredYrFlood2/unnamed-chunk-5-1.png"&gt;&lt;/p&gt;
&lt;p&gt;In a 37-year period, it's much more likely to have zero 100-year floods than to have one. Still, the probability of exactly one is high, about 26%.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Probability of exactly 1 100-year flood in 37 years&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Expected Binomial Counts&lt;/td&gt;
&lt;td&gt;0.25767&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Simulated Binomial Counts&lt;/td&gt;
&lt;td&gt;0.257&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Expected Poisson  Counts&lt;/td&gt;
&lt;td&gt;0.25557&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Simulated Poisson Counts&lt;/td&gt;
&lt;td&gt;0.258&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Counts of Simulated Floods&lt;/td&gt;
&lt;td&gt;0.261&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;p&gt;Ladson, Tony. "The 100 year flood." &lt;em&gt;tonyladson | Hydrology, Natural Resources and R&lt;/em&gt;. June 7, 2015. https://tonyladson.wordpress.com/2015/06/07/the-100-year-flood/.&lt;/p&gt;
&lt;p&gt;https://water.usgs.gov/edu/100yearflood.html&lt;/p&gt;
&lt;p&gt;https://water.usgs.gov/edu/100yearflood-basic.html&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="R"></category></entry></feed>