【问题标题】:R: Using smooth.spline within a functionR:在函数中使用 smooth.spline
【发布时间】:2020-05-22 11:24:52
【问题描述】:

我正在尝试按照Karsten W 的建议使用smooth.spline 创建一条平滑线。我创建了一个简单的数据集,我在函数中调用它来绘制绘图。它已根据Parfait here 的建议进行汇总。

我正在尝试使用 smooth.spline 来创建最适合绘制的点,但要使其工作,我需要它只调用函数中的临时数据集,这是我无法做到的。

下面是一个独立的代码:

d1 <- c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
d2 <- c(1:12)
d3 <- c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2)
df <- cbind(d1, d2, d3)
rm(d1, d2, d3)

average_plot <- function(a, b) {
  for_plot <- aggregate(reformulate(a, b), df, mean)
  smoothingSpline = smooth.spline(reformulate(a, b), spar=0.35)
  plot(reformulate(a, b), for_plot)
  lines(smoothingSpline)
}
average_plot("d1", "d3")

(我不得不承认我不太了解reformulate(a, b) 位,因为虽然它有效,但它与手册中显示的语法不同。)

任何帮助将不胜感激!

【问题讨论】:

    标签: r plot curve-fitting


    【解决方案1】:

    你很亲密。您的链接答案使用d2 作为x 轴上的值,因此实际上您不需要考虑d3smooth.spline 函数没有数据参数,所以我们需要使用with。最好不要在函数中“硬编码”数据,因此我们将dat 作为另一个参数。

    dat <- data.frame(d1=c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4), 
                     d2=1:12)
    
    average_plot <- function(a, b, dat) {
      for_plot <- aggregate(reformulate(a, b), dat, mean)
      smoothingSpline <- with(for_plot, smooth.spline(reformulate(a, b), spar=0.35))
      plot(reformulate(a, b), for_plot)
      lines(smoothingSpline)
    }
    

    结果

    average_plot(a="d1", b="d2", dat)
    

    【讨论】:

    • 非常感谢。我对此并不陌生,with 的使用对我来说也不清楚,非常感谢。我知道第三个变量没用,但认为将它留在那里只是为了表明我需要一个函数而不仅仅是一个直接的情节:o ...否则,你有没有参考,我可以更好地理解reformulate()aggregate()内部使用
    • 这并不神奇,只需尝试reformulate("d1", "d2")。您可以使用? 查找每个 R 函数的帮助页面,例如键入?reformulate 进入你的 R 控制台。
    猜你喜欢
    • 2015-06-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多