【问题标题】:Creating a function that names objects created based on a function in R创建一个函数,该函数命名基于 R 中的函数创建的对象
【发布时间】:2018-04-19 23:34:22
【问题描述】:

我有一个关于创建创建 ggplots 的函数的问题。我想创建自己的函数来快速绘制多个数据帧中的值,而不是编写一个完整的 ggplot,每次都填写每个参数。我想要做的是输入数据框名称的向量,让函数创建图形并将每个图形保存为具有不同名称的新对象。我的想法的例子是……

myfunction <- function(x) {
              ggplot(x, aes(x = time, y = result)) +
                           geom_point()
}

我希望能够做类似的事情

myfunction(c(testtype1, testtype2, testtype3)) 

并让函数创建对象 plot1、plot2、plot3。目前我只能做

plot1 <- myfunction(testtype1)
plot2 <- myfunction(testtype2)
plot3 <- myfunction (testtype3)

我不想一遍又一遍地输入,尤其是当我有很多测试类型时。有没有办法可以修改函数以使用函数根据某些公式命名对象?

【问题讨论】:

  • 也许lapply(list(testtype1, testtype2, testtype3), myfunction)
  • 请参阅下面的答案,让我知道这是否有效,您需要更多解释。

标签: r function naming


【解决方案1】:

这样,您可以提供任意数量的(适当的)数据框,l_my_fun 将返回一个包含图的列表。

l_my_fun <- function(x, ...) {
  l <- list(x, ...)
  ps <- lapply(l, myfunction)
  ps
}

out <- l_my_fun(testtype1, testtype2, testtype3)

例如,现在访问第二个图

out[[2]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2013-01-02
    相关资源
    最近更新 更多