我正在尝试按照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)位,因为尽管它可以工作,但它与手册中显示的语法不同。)
任何帮助都将不胜感激!
发布于 2020-05-22 20:29:56
你们已经很接近了。您的链接答案对x轴上的值使用smooth.spline,因此实际上您不需要考虑with。smooth.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)

https://stackoverflow.com/questions/61953921
复制相似问题