简体   繁体   English

ifel循环的有效替代方案

[英]Efficient alternative to for loop of ifelse

Would be some so kind and suggest fast solution (vectorised & data.table) solution? 会是一些如此善良并建议快速解决方案(矢量化和data.table)解决方案?

Here is sample data and current loop: 这是样本数据和当前循环:

set.seed(123)
df <- data.frame(x=abs(rnorm(10)*100),y=abs(rnorm(10)*100))
df$ratio <- df$x/df$y

for(i in 1:nrow(df)) {
df[,c("x")][i] <- ifelse(df[,c("ratio")][i]>1.5,1.5*df[,c("y")][i],df[,c("x")][i])
}

So I'm replacing column x values if the ration is greater than 1.5 因此,如果比率大于1.5我将替换列x

try 尝试

library(data.table)
setDT(df)[ratio > 1.5, x := 1.5*y]

Or a base R solution base R解决方案

transform(df, x=ifelse(ratio > 1.5, 1.5*y, x))

Benchmarks 基准

set.seed(123)
df1 <- data.frame(x=abs(rnorm(1e6)*100),y=abs(rnorm(1e6)*100))
df1$ratio <-df1$x/df1$y
f1 <- function(){ as.data.table(df1)[ratio > 1.5, x:= 1.5*y]}

f2 <- function(){ indx <- df1$ratio > 1.5
                df1$x[indx] <- df1$y[indx]*1.5}

f3 <- function(){transform(df1, x=ifelse(ratio > 1.5, 1.5*y, x))}

#Another option suggested by @Steven Beaupré
f4 <- function(){mutate(df1, x=ifelse(ratio > 1.5, 1.5*y, x))}

 microbenchmark(f1(),f2(),f3(),f4(), unit='relative', times=40L)
 #Unit: relative
 #expr       min        lq     mean    median       uq      max neval cld
 #f1()  1.000000  1.000000 1.000000  1.000000 1.000000 1.000000    40 a  
 #f2()  2.829316  2.749836 2.047366  2.645489 1.301990 2.070973    40 b 
 #f3() 12.693416 12.954443 9.060991 12.689862 6.170528 7.935411    40 c
 #f4() 13.231567 13.300574 9.147105 12.636984 6.217343 6.286193    40 c

Another option in base R: 基地R的另一个选择:

indx <- df$ratio > 1.5
df$x[indx] <- df$y[indx] * 1.5

This will likely be pretty fast even with relatively big data sets. 即使数据集相对较大,这也可能非常快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM