Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Split a row into columns with conditions in R

$
0
0

I've a dataframe as under

+----+-------+---------+
| ID | VALUE |  DATE   |
+----+-------+---------+
|  1 |    10 | 2019-08 |
|  2 |    12 | 2018-05 |
|  3 |    45 | 2019-03 |
|  3 |    33 | 2018-03 |
|  1 |     5 | 2018-08 |
|  2 |    98 | 2019-05 |
|  4 |    67 | 2019-10 |
|  4 |    34 | 2018-10 |
|  1 |    55 | 2018-07 |
|  2 |    76 | 2019-08 |
|  2 |    56 | 2018-12 |
+----+-------+---------+

What I'm trying to do here is to split the value and date into value1 and value2 and data1 and date2 based on the current year(year of systemdate) and the year before

But the condition here is if the date-month combination in DATE of the main table matched to that of current systemdate then donot consider last years date

Also disregard all the values dates that appear before the year of systemdate The resulting output would be as under

Over here in the result ID 1,2 and 3 had corresponding values for same month in this year and last year so we split them in 2 different columns Also we didn't consider last years result of ID 4 as its month this year matches with year-month combination of systemdate and we also disregard all the values from lat year that don't have a corresponding month match this year ( ID 1 for 2018-07 and 2 for 2018-12 in this example)

+----+---------+---------+--------+--------+
| ID |  DATE1  |  DATE2  | VALUE1 | VALUE2 |
+----+---------+---------+--------+--------+
|  1 | 2019-08 | 2018-08 |     10 | 5      |
|  2 | 2019-05 | 2018-05 |     98 | 12     |
|  3 | 2019-03 | 2018-03 |     45 | 33     |
|  4 | 2019-10 | NA      |     67 | NA     |
|  2 | 2019-08 | NA      |     76 | NA     |
+----+---------+---------+--------+--------+

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>