R-确实将整个数据框传递到函数或仅几列在计算速度方面有所不同



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

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

最新更新