通过在 R 中使用矢量化函数,您可以在一个函数调用中测试所有行。您可以在下面的示例中看到我的代码快了 50 倍。
在这种情况下,if_else 是 ifelse 的矢量化版本,str_detect 是 grep 的矢量化版本。 tidyverse 包和管道提供了函数 select 和 mutate,这使得使用矢量化函数操作数据帧变得容易。
library(tidyverse)
n <- 10000
sampledata <- data.frame(aa=rbinom(n, 1, 0.5), b = rep("bvalue", n), stringsAsFactors = FALSE) %>%
mutate(a = if_else(aa == 0, "nothing", "OK")) %>%
select(a, b, -aa)
yourcode <- function(sampledata) {
newdata <- sampledata
for(i in 1:nrow(sampledata)){
if(!is.na(grep('OK', sampledata$a[i])[1])){
b <- sampledata$b[i]
newdata$b[i] <- sampledata$a[i]
newdata$a[i] <- b
}
}
return(newdata)
}
# using vectorized functions and tidyverse will make your code faster
mycode <- function(sampledata) {
newdata <- sampledata %>% mutate(new_b = if_else(str_detect(a, "OK"), a, b),
new_a = if_else(str_detect(a, "OK"), b, a)) %>%
select(-a, -b, a = new_a, b = new_b)
return(newdata)
}
system.time(yourcode(sampledata))
#> user system elapsed
#> 1.46 0.03 1.56
system.time(mycode(sampledata))
#> user system elapsed
#> 0.03 0.00 0.03
由reprex package (v0.2.1) 于 2019 年 2 月 20 日创建