how can I mutate in dplyr without losing order?

谁都会走 提交于 2020-01-11 08:38:30

问题


Using data.table I can do the following:

library(data.table)
dt = data.table(a = 1:2, b = c(1,2,NA,NA))
#   a  b
#1: 1  1
#2: 2  2
#3: 1 NA
#4: 2 NA

dt[, b := b[1], by = a]
#   a b
#1: 1 1
#2: 2 2
#3: 1 1
#4: 2 2

Attempting the same operation in dplyr however the data gets scrambled/sorted by a:

library(dplyr)
dt = data.table(a = 1:2, b = c(1,2,NA,NA))
dt %.% group_by(a) %.% mutate(b = b[1])
#  a b
#1 1 1
#2 1 1
#3 2 2
#4 2 2

(as an aside the above also sorts the original dt, which is somewhat confusing for me given dplyr's philosophy of not modifying in place - I'm guessing that's a bug with how dplyr interfaces with data.table)

What's the dplyr way of achieving the above?


回答1:


In the current development version of dplyr (which will eventually become dplyr 0.2) the behaviour differs between data frames and data tables:

library(dplyr)
library(data.table)

df <- data.frame(a = 1:2, b = c(1,2,NA,NA))
dt <- data.table(df)

df %.% group_by(a) %.% mutate(b = b[1])

## Source: local data frame [4 x 2]
## Groups: a
## 
##   a b
## 1 1 1
## 2 2 2
## 3 1 1
## 4 2 2

dt %.% group_by(a) %.% mutate(b = b[1])

## Source: local data table [4 x 2]
## Groups: a
## 
##   a b
## 1 1 1
## 2 1 1
## 3 2 2
## 4 2 2

This happens because group_by() applied to a data.table automatically does setkey() on the assumption that the index will make future operations faster.

If there's a strong feeling that this is a bad default, I'm happy to change it.



来源:https://stackoverflow.com/questions/21716364/how-can-i-mutate-in-dplyr-without-losing-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!