I am new to data.table & trying to replicate some dplyr code but not getting same results when I mutate columns.
libs
library(data.table)
library(lubridate)
library(tidyverse)
df
test_df <- data.frame(id = c(1234, 1234, 5678, 5678),
date = c("2021-10-10","2021-10-10", "2021-8-10", "2021-8-15"),
Amount = c(54767, 96896, 34534, 79870)) %>%
mutate(date = ymd(date))
dplyr code:
test_df %>%
group_by(id) %>%
arrange(date) %>%
mutate(Amt_first = first(Amount),
Amt_last = last(Amount)) %>%
ungroup()
results:
# A tibble: 4 x 5
id date Amount Amt_first Amt_last
<dbl> <date> <dbl> <dbl> <dbl>
1 5678 2021-08-10 34534 34534 79870
2 5678 2021-08-15 79870 34534 79870
3 1234 2021-10-10 54767 54767 96896
4 1234 2021-10-10 96896 54767 96896
data.table attempt (returns me nothing):
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id]
I am not sure what is wrong, it seems its not selecting any columns but I as am mutating columns so ideally it should return all the columns.
CodePudding user response:
This is described in data.table's FAQ - 2.23.
You just need to add an extra []
at the end of your code:
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id][]
id date Amount Amt_first Amt_last
1: 1234 2021-10-10 54767 54767 96896
2: 1234 2021-10-10 96896 54767 96896
3: 5678 2021-08-10 34534 34534 79870
4: 5678 2021-08-15 79870 34534 79870