lomper
lomper

Reputation: 379

R: Using smooth.spline within a function

I am trying to create a smooth line using smooth.spline following advice from Karsten W. I have created a simple dataset which I call inside a function to draw plots. It has been aggregated following advice from Parfait here.

I am trying to get use smooth.spline to create a best fit for the points plotted, but for it to work I'd need it to call only the temporary dataset within the function, which I am unable to do.

Below a self-contained code :

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")

(I have to confess that I do not quite understand the reformulate(a, b) bit since, although it works, it is unlike the syntax shown in the manual.)

Any help would be very appreciated!

Upvotes: 1

Views: 245

Answers (1)

jay.sf
jay.sf

Reputation: 73602

You were close. Your linked answers use d2 for the values on the x-axis, so actually you don't need to take d3 into account. The smooth.spline function has no data argument, so we need to use with. It's better not to "hardcode" the data within a function, so we take up dat as another argument.

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)
}

Result

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

enter image description here

Upvotes: 1

Related Questions