Search code examples
rdataframerstudiocovariancerollapply

How can I find Covariance for every n row in R


I have 2 large set of data, each have 2000+ data and trying to find the covariance for every 5 row.

x=c(1,2,3,4,5)
y=c(6,7,8,9,10)
df=data.frame(x,y)
group=rep(1:length(df),each=2,length=length(df))

What is my next step so I can find the covariance like this`

cov(x[1:2,],y[1:2,])

and

cov(x[3:4,],y[3:4,])

Solution

  • library(zoo)    
    x = c(1,2,3,4,5)
    y = c(6,7,8,9,10)
    rows = 2
    out = rollapply(data.frame(x,y), rows, function(x) cov(x[,1],x[,2]),
                        by.column=FALSE)
    out