假设我有一个包含大量列的数据框
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/