【发布时间】:2021-08-28 13:55:08
【问题描述】:
混合tidyverse 和data.table 语法时,我得到了一些非常奇怪的行为。
对于上下文,我经常发现自己使用tidyverse 语法,然后在我需要速度与需要代码可读性时将管道添加回data.table。我知道 Hadley 正在开发一个使用 tidyverse 语法和 data.table 速度的新包,但据我所知,它仍处于初期阶段,所以我没有使用它。
有人愿意解释这里发生了什么吗?这对我来说非常可怕,因为我可能已经不假思索地做了数千次。
library(dplyr); library(data.table)
DT <-
fread(
"iso3c country income
MOZ Mozambique LIC
ZMB Zambia LMIC
ALB Albania UMIC
MOZ Mozambique LIC
ZMB Zambia LMIC
ALB Albania UMIC
"
)
codes <- c("ALB", "ZMB")
# now, what happens if I use a tidyverse function (distinct) and then
# convert back to data.table?
DT <- distinct(DT) %>% as.data.table()
# this works like normal
DT[iso3c %in% codes]
# iso3c country income
# 1: ZMB Zambia LMIC
# 2: ALB Albania UMIC
# now, what happens if I use a different tidyverse function (arrange)
# and then convert back to data.table?
DT <- DT %>% arrange(iso3c) %>% as.data.table()
# this is wack: (!!!!!!!!!!!!)
DT[iso3c %in% codes]
# iso3c country income
# 1: ALB Albania UMIC
# but these work:
DT[(iso3c %in% codes), ]
# iso3c country income
# 1: ZMB Zambia LMIC
# 2: ALB Albania UMIC
DT[DT$iso3c %in% codes, ]
# iso3c country income
# 1: ZMB Zambia LMIC
# 2: ALB Albania UMIC
DT[DT$iso3c %in% codes]
# iso3c country income
# 1: ZMB Zambia LMIC
# 2: ALB Albania UMIC
【问题讨论】:
标签: r dplyr data.table tidyverse