r语言 - 如何对data.table进行排序、分组、修改?



我是新手data.table,试图复制一些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))

dplyr代码:

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]

我不知道什么是错的,它似乎没有选择任何列,但我作为突变列,所以理想情况下,它应该返回所有列。

这在data中有说明。表的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

最新更新