首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R:在函数中使用smooth.spline

R:在函数中使用smooth.spline
EN

Stack Overflow用户
提问于 2020-05-22 19:24:53
回答 1查看 58关注 0票数 1

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

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

下面是一个自包含的代码:

代码语言:javascript
复制
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)位,因为尽管它可以工作,但它与手册中显示的语法不同。)

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-22 20:29:56

你们已经很接近了。您的链接答案对x轴上的值使用smooth.spline,因此实际上您不需要考虑withsmooth.spline函数没有数据参数,因此我们需要使用with。最好不要在函数中对数据进行“硬编码”,因此我们将dat作为另一个参数。

代码语言:javascript
复制
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)
}

结果

代码语言:javascript
复制
average_plot(a="d1", b="d2", dat)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61953921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档