I am new to data.table & trying to reorder columns in data.table code.
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() %>%
select(Amt_first, Amt_last, everything())
data.table attempt:
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id][, union(c("Amt_first", "Amt_last"), names(test_df))]
# result
[1] "Amt_first" "Amt_last" "id" "date" "Amount"
I have also tried: [, .(union(c("Amt_first", "Amt_last"), names(test_df)))]
but didn't get desired results.
I am not sure why above code doesn't return expected results.
I am aware of setcolorder()
but I am interested in implementing the above code without setcolorder as setcolorder doesn't print the results in chaining.