R:在函数中使用smooth.spline

问题描述 投票:1回答:1

我正在尝试根据smooth.spline的建议使用Karsten W创建平滑线。我已经创建了一个简单的数据集,可以在函数内调用该数据集来绘制曲线。已根据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个回答
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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.