Merge data.frame by Date (year and month)
<h1>1st Case</h1>

<p>I have got two data.frames as follow:</p>

<pre><code>df1 = read.table(text = 'Date  ID
1980-12-01  2
1982-11-01  1
1990-01-01  6
1993-07-01  9', header = TRUE)

df2 = read.table(text = 'Date  Var
1980-12-17  8
1982-11-07  9
1990-01-19  10
1993-07-20  22', header = TRUE)
</code></pre>

<p>I need to merge df1 with df2 by the column Date but by only considering the Year and Month, also because otherwise the merge does not work (because the Days are different).</p>

<p>My output should be like this:</p>

<pre><code>Date    ID  Var
1980-12  2    8
1982-11  1    9
1990-01  6   10
1993-07  9   22
</code></pre>

<p>I considered to remove the Days in the Date columns but I would like to know if there is a quicker way to do this. I also checked and it seems that no one asked this question before.</p>

<p>Thanks</p>

#

<p>UPDATE</p>

<h1>2nd Case</h1>

<p>As suggested in the comments, what if I have got multiple observations in the same Year and Month in one data.frame?</p>

<p>e.g.</p>

<pre><code>df1 = read.table(text = 'Date  ID #as 1st Case
1980-12-01  2
1982-11-01  1
1990-01-01  6
1993-07-01  9', header = TRUE)

df3 = read.table(text = 'Date  Var
    1980-12-17  8
    1980-12-29  4
    1980-12-30  1
    1982-11-07  9
    1982-11-12  1
    1990-01-19  10
    1990-01-22  21
    1993-07-20  22
    1993-07-26  12', header = TRUE)
</code></pre>

<p>My new output should be:</p>

<pre><code>Date   Var    ID
1980-12  8     2
1980-12  4     2
1980-12  1     2
1982-11  9     1
1982-11  1     1
1990-01  10    6
1990-01  21    6
1993-07  22    9
1993-07  12    9
</code></pre>

#

<p>UPDATE</p>

<h1>3rd Case</h1>

<p>What if I have got multiple observations in the same Year and Month in both the data.frames?</p>

<pre><code>df4 = read.table(text = 'Date  ID 
    1980-12-01  1
    1980-12-01  2
    1982-11-01  3
    1982-11-01  4
    1990-01-01  5
    1990-01-01  6
    1993-07-01  7
    1993-07-01  8', header = TRUE)

df3 = read.table(text = 'Date  Var      #as 2nd Case
    1980-12-17  8
    1980-12-29  4
    1980-12-30  1
    1982-11-07  9
    1982-11-12  1
    1990-01-19  10
    1990-01-22  21
    1993-07-20  22
    1993-07-26  12', header = TRUE)
</code></pre>

<p>The new output should be:</p>

<pre><code>    Date       Var  ID
    1980-12-17   8   1
    1980-12-17   8   2
    1980-12-29   4   1
    1980-12-29   4   2
    1980-12-30   1   1
    1980-12-30   1   2
    1982-11-07   9   3
    1982-11-07   9   4
    1982-11-12   1   3
    1982-11-12   1   4
    1990-01-19   10  5
    1990-01-19   10  6
    1990-01-22   21  5
    1990-01-22   21  6
    1993-07-20   22  7
    1993-07-20   22  8
    1993-07-26   12  7
    1993-07-26   12  8
</code></pre>