假设我有一个包含大量列的数据框

ncol = 40
sample_size = 300

my_matrix <- replicate(ncol, runif(sample_size, 0, 3))
my_df <- data.frame(my_matrix)
names(my_df) <- paste0("x", 1:ncol)
epsilon <- rnorm(sample_size, 0, 0.2)
my_df$y <- 1+3*my_df$x1 + epsilon


我将数据帧传递给一个仅需要其三列即可完成工作的函数(在我的真实代码中,该函数可能会使用3列以上,但我想在这里简化一下):

library(ggplot2)

idle_plotter <- function(dataframe, x_string, y_string, color_string){
    p <- ggplot(dataframe, aes_string(x = x_string, y = y_string, color = color_string)) +
        geom_point()
    print(p)
}


如果将整个my_df传递给idle_plotter,或者只是idle_plotter所需的三列,那么在速度方面是否有所不同?如果整个数据帧都在调用时被复制,我想是的,但是如果R是按引用传递的,那不应该。在我的测试中,这似乎没有什么不同,但是我需要知道是否:


这是一条规则,在这种情况下,我可以继续将数据帧传递给函数
或只是傻瓜,因为功能简单和/或数据帧不大。在这种情况下,我必须放弃传递完整数据帧的习惯,否则我就有使我的代码比现在慢的风险。

最佳答案

似乎没有什么大不同:使用数据运行

idle_plotter_df <- function(dataframe, x_string, y_string, color_string){
    p <- ggplot(dataframe, aes_string(x = x_string, y = y_string, color = color_string)) +
        geom_point()
    print(p)
}

idle_plotter_col <- function(x_string, y_string, color_string){
  p <- ggplot(NULL) + aes_string(x = x_string, y = y_string, color = color_string) +
    geom_point()
  print(p)
}

microbenchmark::microbenchmark(
  idle_plotter_df(my_df, "x1", "x2", "x3"),
  idle_plotter_col("my_df$x1", "my_df$x2", "my_df$x3"), times = 10L)


结果

Unit: milliseconds
                                                 expr      min       lq     mean   median       uq      max neval
             idle_plotter_df(my_df, "x1", "x2", "x3") 168.8718 260.0504 265.3658 270.8738 272.5409 323.3371    10
 idle_plotter_col("my_df$x1", "my_df$x2", "my_df$x3") 264.6850 276.4981 293.8205 284.9820 300.3936 356.9910    10

07-25 23:24
查看更多