Subtracting a fitted polynomial from a dataset in R

Viewed 195

I have one curve, a scatterplot, which is the plot of the data set I am working with (named 'mydata') and the other curve which is the fitted 2nd degree polynomial curve that I obtained from the data set. The scatterplot was obtained with a simple plot function:

plot(mydata)

The code I used for the fitting is:

fit<-lm(mydata$Volts ~ poly(mydata$Frequency, 2, raw=TRUE),data=mydata)
#summary(fit)
lines(mydata$Frequency, predict(fit))

Now, I would like to subtract the fitted polynomial from the dataset. Following was my approach:

given<-plot(mydata)
fit<-lm(mydata$Volts ~ poly(mydata$Frequency, 2, raw=TRUE),data=mydata)
new<-lines(mydata$Frequency, predict(fit))
corrected<-given-new
plot(corrected)

The error I received was:

Error in plot(corrected) : object 'corrected' not found

How do I correct this?

2 Answers

Looks like you are trying to subtract graphical elements. You should perform any math/operations on your data before trying to plot it. Something like the following may work. However without sample data this is just an educated guess.

given <- mydata$Volts
fit <- lm(mydata$Volts ~ poly(mydata$Frequency, 2, raw=TRUE),data=mydata)
new <- predict(fit)
corrected <- given-new
plot(mydata$Frequency, corrected)

I ran a reprex (although technically, I need a random seed for a true reprex, but because of the actual issue with the code, that doesn't matter here) on nonsense data.

volts=rnorm(50,mean=220,sd=5)
frequency=runif(50,min=30,max=90)

mydata=data.frame(Volts=volts,Frequency=frequency)
given<-plot(mydata)
fit<-lm(mydata$Volts ~ poly(mydata$Frequency, 2, raw=TRUE),data=mydata)
new<-lines(mydata$Frequency, predict(fit))
corrected<-given-new
plot(corrected)

The scope of my answer is strictly to explain why the not found error showed up. Daniel's code shows you the fix.

I'm not sure why the response of Daniel O was not chosen, because it worked. I know it is frustrating when you clearly defined something and your source code is right in front of you, yet the interpreter says NOT FOUND. The lesson learned here when you get this situation, to check for NULL. It's a good habit in general for R.

Related