R:在函数中使用 smooth.spline
R: Using smooth.spline within a function
我正在尝试根据 Karsten W. I have created a simple dataset which I call inside a function to draw plots. It has been aggregated following advice from 的建议使用 smooth.spline
创建平滑线。
我正在尝试使用 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)
位,因为尽管它有效,但它与手册中显示的语法不同。)
如有任何帮助,我们将不胜感激!
你很接近。您的链接答案使用 d2
作为 x 轴上的值,因此实际上您不需要考虑 d3
。 smooth.spline
函数没有数据参数,所以我们需要使用 with
。最好不要 "hardcode" 函数中的数据,所以我们将 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)
我正在尝试根据 Karsten W. I have created a simple dataset which I call inside a function to draw plots. It has been aggregated following advice from smooth.spline
创建平滑线。
我正在尝试使用 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)
位,因为尽管它有效,但它与手册中显示的语法不同。)
如有任何帮助,我们将不胜感激!
你很接近。您的链接答案使用 d2
作为 x 轴上的值,因此实际上您不需要考虑 d3
。 smooth.spline
函数没有数据参数,所以我们需要使用 with
。最好不要 "hardcode" 函数中的数据,所以我们将 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)