【发布时间】:2021-05-21 15:56:48
【问题描述】:
由于性能提高,我将很多数据操作管道从 dplyr 切换到 data.table。我喜欢 a[b] 连接语法的简洁性。 dplyr::left_join(x, y) 对应于data.table 中的y[x]。但是,在这两种情况下,列顺序是不同的。有没有办法复制从 dplyr left_join 获得的列顺序,其中来自 y 的新列被添加到 x 的右侧,使用 data.table 的 y[x] 语法?我知道你可以使用merge(x, y, all.x = TRUE),但我很好奇[] 方式是否可以达到相同的效果。
示例
library(dplyr)
library(data.table)
x <- iris
y <- data.frame(Species = c('setosa', 'virginica'), foo = c(100, 200))
j1 <- left_join(x, y)
setDT(x)
setDT(y)
j2 <- y[x, on = 'Species']
j3 <- merge(x, y, all.x = TRUE)
如何使j2 与j1 和j3 具有相同的列顺序?
> head(j1, 1)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species foo
1: 5.1 3.5 1.4 0.2 setosa 100
> head(j2, 1)
Species foo Sepal.Length Sepal.Width Petal.Length Petal.Width
1: setosa 100 5.1 3.5 1.4 0.2
> head(j3, 1)
Species Sepal.Length Sepal.Width Petal.Length Petal.Width foo
1: setosa 5.1 3.5 1.4 0.2 100
【问题讨论】:
标签: r dplyr data.table