0

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.

ViSa
  • 1,563
  • 8
  • 30
  • Something like: `mycols = unique(c("Amt_first", "Amt_last"), names(test_df)); test_df[, ..mycols]` – zx8754 Oct 19 '21 at 08:21
  • 1
    thanks @zx8754 , yes this worked but I was looking for chain operation without any saving !! – ViSa Oct 19 '21 at 08:25
  • 1
    Use with = FALSE from the linked post: `test_df[, unique(c("Amt_first", "Amt_last"), names(test_df)), with = FALSE]` – zx8754 Oct 19 '21 at 08:47
  • 1
    @zx8754, yes this is what I was looking for & it worked well.. thanks again. Appreciate your help !! – ViSa Oct 19 '21 at 09:04

0 Answers0