我是data.table的新手&尝试复制一些dplyr代码,但在变异列时却没有得到相同的结果。
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代码:
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 96896data.table尝试(不返回任何内容):
setDT(test_df)[order(date),
`:=`(Amt_first = data.table::first(Amount),
Amt_last = data.table::last(Amount)),
by = id]我不知道出了什么问题,它似乎没有选择任何列,但我作为变异列,所以理想情况下,它应该返回所有的列。
发布于 2021-10-18 08:28:28
这在数据表的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 79870https://stackoverflow.com/questions/69612772
复制相似问题