Zettelkasten

top

meta.zscore <- function(fc1, fc2, pval1, pval2, n1, n2) {
  nsum <- n1 + n2
  w1 <- sqrt(n1) / sqrt(nsum);
  w2 <- sqrt(n2) / sqrt(nsum);

  convert.pvalue.to.zscore <- function(pval, beta) {
    if ( beta > 0 ) {
      z <- qnorm( pval / 2 );
    } else {
      z <- -(qnorm( pval / 2 ));
    }

    return(z);
  }

  p.to.z <- function(pval1, pval2, fc1, fc2, w1, w2) {
    z1 <- convert.pvalue.to.zscore(pval1, fc1);
    z2 <- convert.pvalue.to.zscore(pval2, fc2);
    zsum <- ( w1*z1 ) + ( w2*z2 )

    return(zsum);
  }

  zmeta <- p.to.z(pval1, pval2, fc1, fc2, w1, w2);
  pmeta <- pnorm(-(abs(zmeta))) * 2;
  return(pmeta)
}


meta.zscore.df <- function(df, l.p.val, r.p.val, l.fc, r.fc, l.n, r.n) {
  for (i in 1:nrow(df)) {
    row <- df[i, ]

    if (!is.na(row[l.p.val]) && !is.na(row[r.p.val])) {
      df[i, "meta.p"] <- meta_zscore(
        as.numeric(row[l.fc]), as.numeric(row[r.fc]),
        as.numeric(row[l.p.val]), as.numeric(row[r.p.val]),
        as.numeric(l.n), as.numeric(r.n)
      )
    }
  }

  df[, "meta.p.adj.bh"] <- p.adjust(
    p = df$meta.p,
    method = "BH",
    n = nrow(df)
  )

  df
}