# Re: [R] Time-varying correlation calculation

From: Tim Hesterberg <timh_at_insightful.com>
Date: Tue 23 Jan 2007 - 19:26:35 GMT

You can do this using an interaction of bs(time) and x, e.g.:

# Time-varying coefficient
x <- rnorm(100)
time <- ppoints(100)
y <- sin(time) + cos(time)*x + rnorm(100)/10

library("splines")
fit <- lm(y ~ bs(time, df=5) * x)
fit
# Plot estimated intercept vs time
plot(time, coef(fit)[1] + bs(time, df=5) %*% coef(fit)[2:6]) lines(time, sin(time))
# Plot estimated slope vs time
plot(time, coef(fit)[7] + bs(time, df=5) %*% coef(fit)[8:12]) lines(time, cos(time))

Thanks to Trevor Hastie for suggesting this approach, when I made a similar query on S-news years ago.

Tim Hesterberg

> I'm interested in getting a series of time-varying correlation, simply between two random variables.
>
>
> Thank you so much for any help.
> Amir

```| Tim Hesterberg       Senior Research Scientist       |
| timh@insightful.com  Insightful Corp.                |
| (206)802-2319        1700 Westlake Ave. N, Suite 500 |
| (206)283-8691 (fax)  Seattle, WA 98109-3044, U.S.A.  |
|                      www.insightful.com/Hesterberg   |
========================================================
```