代码之家  ›  专栏  ›  技术社区  ›  ViSa

如何在data.table中进行排序、分组和变异?

  •  0
  • ViSa  · 技术社区  · 5 年前

    我是新手 &试图复制一些 dplyr 代码,但当我 变异 柱。

    自由基

    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))
    

    test_df %>% 
      group_by(id) %>% 
      arrange(date) %>% 
      mutate(Amt_first = first(Amount),
             Amt_last = last(Amount)) %>%
      ungroup()
    

    结果:

    # 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
    

    setDT(test_df)[order(date),
                 `:=`(Amt_first = data.table::first(Amount),
                       Amt_last = data.table::last(Amount)), 
                 by = id]
    

    我不确定是什么错了,它似乎没有选择任何列,但我正在改变列,所以理想情况下它应该返回所有列。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Waldi    5 年前

    这在中进行了描述 data.table's FAQ - 2.23 .
    你只需要再加一个 [] 在代码末尾:

    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