r - 将整个数据帧传递给函数还是仅将几列传递给计算速度会有所不同?

标签 r parameter-passing pass-by-reference

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

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
    

    关于r - 将整个数据帧传递给函数还是仅将几列传递给计算速度会有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685244/

    相关文章:

    C++ 传递 vector<vector<STRUCT>> 进行修改

    c++ - 构造函数中的临时非常量 istream 引用 (C++)

    c++ - 在循环迭代期间在 vector 中保存对 void 指针的引用

    r - 如何单击传单 map ,创建标记,然后在单击 R 中的其他位置时删除该标记

    r - 如何在没有坐标极的情况下制作堆积圆图

    r - ggplot2不知道如何处理 react 类的数据

    jQuery colorbox - 从单击的链接获取 url 参数

    r - 使用 R 动画包在磁盘上使用图像文件

    c++ - 将 vector 、队列和指针传递给函数

    c - 在 C 中修改链表项的正确方法