问题描述
我正在尝试找出一种简单的方法来使用 dplyr(数据集 = dat,变量 = x)执行此类操作:
I'm trying to figure out a simple way to do something like this with dplyr (data set = dat, variable = x):
day$x[dat$x<0]=NA
应该很简单,但这是我目前能做的最好的.有没有更简单的方法?
Should be simple but this is the best I can do at the moment. Is there an easier way?
dat = dat %>% mutate(x=ifelse(x<0,NA,x))
推荐答案
你可以使用 replace
比 ifelse
快一点:
You can use replace
which is a bit faster than ifelse
:
dat <- dat %>% mutate(x = replace(x, x<0, NA))
您可以通过使用 which
为 replace
提供索引来加快速度:
You can speed it up a bit more by supplying an index to replace
using which
:
dat <- dat %>% mutate(x = replace(x, which(x<0L), NA))
在我的机器上,这将时间缩短到三分之一,见下文.
On my machine, this cut the time to a third, see below.
这里是对不同答案的一些比较,当然只是指示性的:
Here's a little comparison of the different answers, which is only indicative of course:
set.seed(24)
dat <- data.frame(x=rnorm(1e6))
system.time(dat %>% mutate(x = replace(x, x<0, NA)))
User System elapsed
0.03 0.00 0.03
system.time(dat %>% mutate(x=ifelse(x<0,NA,x)))
User System elapsed
0.30 0.00 0.29
system.time(setDT(dat)[x<0,x:=NA])
User System elapsed
0.01 0.00 0.02
system.time(dat$x[dat$x<0] <- NA)
User System elapsed
0.03 0.00 0.03
system.time(dat %>% mutate(x = "is.na<-"(x, x < 0)))
User System elapsed
0.05 0.00 0.05
system.time(dat %>% mutate(x = NA ^ (x < 0) * x))
User System elapsed
0.01 0.00 0.02
system.time(dat %>% mutate(x = replace(x, which(x<0), NA)))
User System elapsed
0.01 0.00 0.01
(我使用的是 dplyr_0.3.0.2 和 data.table_1.9.4)
(I'm using dplyr_0.3.0.2 and data.table_1.9.4)
因为我们总是对基准测试非常感兴趣,特别是在 data.table-vs-dplyr 讨论过程中,我使用 microbenchmark 和 akrun 的数据提供了 3 个答案的另一个基准.请注意,我将 dplyr1
修改为我的答案的更新版本:
Since we're always very interested in benchmarking, especially in the course of data.table-vs-dplyr discussions I provide another benchmark of 3 of the answers using microbenchmark and the data by akrun. Note that I modified dplyr1
to be the updated version of my answer:
set.seed(285)
dat1 <- dat <- data.frame(x=sample(-5:5, 1e8, replace=TRUE), y=rnorm(1e8))
dtbl1 <- function() {setDT(dat)[x<0,x:=NA]}
dplr1 <- function() {dat1 %>% mutate(x = replace(x, which(x<0L), NA))}
dplr2 <- function() {dat1 %>% mutate(x = NA ^ (x < 0) * x)}
microbenchmark(dtbl1(), dplr1(), dplr2(), unit='relative', times=20L)
#Unit: relative
# expr min lq median uq max neval
# dtbl1() 1.091208 4.319863 4.194086 4.162326 4.252482 20
# dplr1() 1.000000 1.000000 1.000000 1.000000 1.000000 20
# dplr2() 6.251354 5.529948 5.344294 5.311595 5.190192 20
这篇关于使用 dplyr 将某些值设置为 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!