简体   繁体   中英

correlation time series in r

I currently have a data set that looks as such (3 variables and a time series):

date       variable    value    
01/01/16      A         1000
01/01/16      B         800
01/01/16      C         10
01/02/16      A         2000
01/02/16      B         1800
01/02/16      C         100
01/03/16      A         100
01/03/16      B         80
01/03/16      C         10

What I'm trying to do is calculate the correlation between all three variables (AB, AC, BC) per day so that I can graph the result as a plot with the date being on the x axis and on the y axis the correlation coefficient (w/ the legend being AB, AC, BC).

Any help would be greatly appreciated!

I think this is what you want:

df <- read.csv(sep=" ",stringsAsFactors=F,text="date variable value
01/01/16 A 1000
01/01/16 B 800
01/01/16 C 10
01/02/16 A 2000
01/02/16 B 1800
01/02/16 C 100
01/03/16 A 100
01/03/16 B 80
01/03/16 C 10 ")
df$date <- strptime(df$date, format = "%m/%d/%y")
df$value <- as.numeric(df$value)

vars <- unique(df$variable)
nv <- length(vars)
npairs <- nv*(nv-1)/2
labs <- rep("", npairs)
cors <- rep(0, npairs)
k <- 1
for (i in 1:(nv-1)) {
    vi <- vars[i]
    si <- df[df$variable == vi,]$value
    for (j in (i+1):nv) {
        vj <- vars[j]
        sj <- df[df$variable == vj,]$value
        labs[k] <- sprintf("%s-%s",vi,vj)
        cors[k] <- cor(si, sj)
        k <- k+1
    }
}
pdf <- data.frame(labs=labs,cors=cors)
ggplot(pdf) + geom_bar(aes(x=labs,y=cors),stat="identity")

yielding: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM