将整个数据帧传递给函数还是仅传递几列会在计算速度方面产生影响?

Does passing a whole dataframe to a function or just few columns make a difference in terms of computational speed?

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

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