我认为一般来说使用%>%不会对速度产生明显影响.但在这种情况下,它运行速度慢了4倍.
library(dplyr)
library(microbenchmark)
set.seed(0)
dummy_data <- dplyr::data_frame(
id=floor(runif(10000, 1, 10000))
, label=floor(runif(10000, 1, 4))
)
microbenchmark(dummy_data %>% group_by(id) %>% summarise(list(unique(label))))
microbenchmark(dummy_data %>% group_by(id) %>% summarise(label %>% unique %>% list))
Run Code Online (Sandbox Code Playgroud)
没有管道:
min lq mean median uq max neval
1.691441 1.739436 1.841157 1.812778 1.880713 2.495853 100
Run Code Online (Sandbox Code Playgroud)
带管:
min lq mean median uq max neval
6.753999 6.969573 7.167802 7.052744 7.195204 8.833322 100
Run Code Online (Sandbox Code Playgroud)
为什么%>%在这种情况下会这么慢?有没有更好的方法来写这个?
我已经阅读了几个关于dplyr编程的指南,我仍然对如何解决使用非标准评估(NSE)评估构造/连接字符串的问题感到困惑.我意识到有更好的方法来解决这个例子,而不是使用NSE,但想要学习如何.
t <- tibble( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
i <- 1
Run Code Online (Sandbox Code Playgroud)
这是我想要的结果,但是想要mutate()构造变量:
t %>% mutate(d_01 = x_01 * 2)
#> A tibble: 3 x 3
#> x_01 x_02 d_01
#> <dbl> <dbl> <dbl>
#> 1 1.00 4.00 2.00
#> 2 2.00 5.00 4.00
#> 3 3.00 6.00 6.00
Run Code Online (Sandbox Code Playgroud)
这是我第一次尝试使用字符串:
new <- sprintf("d_%02d", i)
var <- sprintf("x_%02d", i)
t %>% mutate(new = var * 2)
#> Error in mutate_impl(.data, dots) : …Run Code Online (Sandbox Code Playgroud)