cov_pairwise=function(X,r) {
  p=ncol(X)
  S=matrix(NA, p, p)
  dimnames(S)[[1]]=colnames(X)
  dimnames(S)[[2]]=colnames(X)
  for (i in 1:p) {
    for (j in 1:p) {
      mask <- stats::complete.cases(X[, c(i, j)])
      xi=X[mask, i]
      xj=X[mask, j]
      n=sum(mask)
      S[i, j]=sum((xi-mean(xi))*(1/r[mask])*(xj-mean(xj)))/(n-1)
    }
  }

  return(S)
}
