如何在 data.table 中排序、分组、变异?
How to order, group, mutate in 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
data.table 尝试(return我什么都没有):
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id]
我不确定出了什么问题,它似乎没有选择任何列,但我正在改变列,所以理想情况下它应该 return 所有列。
这在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
我是 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
data.table 尝试(return我什么都没有):
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id]
我不确定出了什么问题,它似乎没有选择任何列,但我正在改变列,所以理想情况下它应该 return 所有列。
这在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