I have 5 columns in my data table id
, created_time
, amount
, balance
, and created_month
. I want the last row for each id
and created_month
, I am trying to get all 5 columns grouped by created_month
and id
.
Input datatable test
:
id created_time amount balance created_month
1 1/15/14 10:17 2 1 1/1/14
1 1/15/14 11:17 2 1 1/1/14
1 1/15/14 20:17 2 1 1/1/14
2 1/15/14 11:17 2 1 1/1/14
2 1/16/14 12:17 2 1 1/1/14
2 2/16/14 23:17 2 1 2/1/14
I have sorted by id
and created_time
as
setkeyv(test, c("id","created_time"))
I need to
- Convert the created_month to show the first day of the month . Similar to date_trunc('month',created_month) in Sql .
- Sort the values by created_time column and get all the columns grouped by 'id' and 'created_month'
The below one only gives me balance since I have only one field in tail option
test[ , tail(balance,1L) , by=c("balanceable_id","created_month" )]
I am not sure how to add multiple fields to tail to display all columns in original table.
My goal is to get this data table:
id created_month created_time amount balance
1 2014-01-01 2014-01-15 20:17:00 2 1
2 2014-01-01 2014-01-16 12:17:00 2 1
2 2014-02-01 2014-02-16 23:17:00 2 1