Need to import data from a .csv file. Turn into time series and plot the time series as well as the linear regression

base-r

#1

I need to import two columns (time and temp) worth of data from a .csv file into R and convert it to a time-series and the plot it with a linear regression line. So far this is my approach:

Wintemp <- read.csv("FileName.csv")
Wintemp.ts <- as.ts(Wintemp)
plot(Wintemp,type="l")

I am able to successfully get a graph of the time series with the code above.

However I am having trouble with plotting the linear regression line. This is the code I have attempted with:

lm(formula = Wintemp) #Gives wrong values as my independent variable is time not temperature.
Call: lm(formula = Wintemp)

Coefficients:

(Intercept)
635.2 

Temp -18.5
Lfit <- 635.3 - 18.5 * Wintemp
ts.plot(Wintemp.ts,Lfit, xlab = "time", ylab = "Temp")

This plots a line but it is far from correct.

I am new to R, could you please help with what the simplest way to perform these set of actions would be? Or what are the mistakes I am making?

Thank you, any help is very much appreciated.


#2

As you are knew to R, I would recommend a few resource on model with R:

Chapter on model in R4DS book

Chapter on model in Modern Dive book

You'll find in both book how to prepare data and how to model with R.

Regarding your issue here, it is kind of difficult to help you because we do not know what Wintemp is. It would help if you could adapt your example to provide a reprex. Thank you!