PageRenderTime 43ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/scripts/helper_functions.R

http://github.com/hpiwowar/alt-metrics_stats
R | 566 lines | 526 code | 15 blank | 25 comment | 213 complexity | fa3674c5578411e06bf11a56aee11afe MD5 | raw file
Possible License(s): MIT
  1. #### HELPER FUNCTIONS
  2. # transform for count data due to
  3. # http://pareonline.net/getvn.asp?v=8&n=6
  4. # if no numbers between 0 and 1, not going to add a +1 offset
  5. tr.0 = function(x) return(sqrt(x))
  6. # using sqrt with minimum value of 1, as per advice at
  7. # http://www.webcitation.org/query?url=http%3A%2F%2Fpareonline.net%2Fgetvn.asp%3Fv%3D8%26n%3D6&date=2010-02-11
  8. tr = function(x) return(sqrt(1 + x))
  9. log.tr = function(x) return(log(1 + x))
  10. #### Some of my variables are extracted by looking to see if MEDLINE records have a MeSH term.
  11. # This is fine, but sometimes MEDLINE records are incomplete, they are in process or aren't on the list
  12. # of journals indexed by MeSH indexers. This means a lack of relevant MeSH term does not mean the MeSH
  13. # term does not apply. Thus, must replace these 0s with NAs to indicate the data is indeed missing
  14. medline.values = function(raw_values, medline_status) {
  15. values = raw_values
  16. values[medline_status!="indexed for MEDLINE"] = NA
  17. return(values)
  18. }
  19. print.thresh = function(x, thresh, decreasing=TRUE) {
  20. response = ""
  21. if (decreasing) {
  22. x.thresh = x[which(x>=thresh)]
  23. } else {
  24. x.thresh = x[which(x<=thresh)]
  25. }
  26. x.sorted = sort(x.thresh, decreasing)
  27. for (ii in 1:length(x.sorted)) {
  28. response = cat(response, sprintf("%f %s\n", x.sorted[ii], names(x.sorted)[ii]))
  29. }
  30. if (length(response>0)) {
  31. print(response)
  32. }
  33. }
  34. ####Get scores:
  35. # based on middle of factanal()
  36. factor.scores.bartlett = function(x, fa.fit, na.action=NULL) {
  37. Lambda <- fa.fit$loadings
  38. z <- as.matrix(x)
  39. if (!is.numeric(z))
  40. # stop("factor analysis applies only to numerical variables")
  41. z = as.matrix(colwise(as.numeric)(x))
  42. zz <- scale(z, TRUE, TRUE)
  43. d <- 1/fa.fit$uniquenesses
  44. tmp <- t(Lambda * d)
  45. scores <- t(solve(tmp %*% Lambda, tmp %*% t(zz)))
  46. rownames(scores) <- rownames(z)
  47. colnames(scores) <- colnames(Lambda)
  48. if (!is.null(na.action))
  49. scores <- napredict(na.act, scores)
  50. scores
  51. }
  52. # Extracted then modified from hetcor.data.frame from polycor
  53. adjust.to.positive.definite = function(inputcor) {
  54. min.eigen = min(eigen(inputcor, only.values=TRUE)$values)
  55. if (min.eigen < 0){
  56. print("will try to make correlation matrix positive-definite")
  57. cor.corrected <- nearcor(inputcor) # also could try nearPD
  58. if (!cor.corrected$converged) {
  59. stop("attempt to make correlation matrix positive-definite failed")
  60. }
  61. print("the correlation matrix has been adjusted to make it positive-definite")
  62. outputcor = cor.corrected$cor
  63. rownames(outputcor) <- rownames(inputcor)
  64. colnames(outputcor) <- colnames(inputcor)
  65. } else {
  66. print("Correlation matrix already positive-definite, so no adjustment needed")
  67. outputcor = inputcor
  68. }
  69. outputcor
  70. }
  71. # Based on hetcore.data.frame from polycor
  72. # Modified slightly to call different correlation function for continuous correlations
  73. # and print out updates
  74. "hetcor.modified" <-
  75. function(data, ML=FALSE, std.err=TRUE, use=c("complete.obs", "pairwise.complete.obs"),
  76. bins=4, pd=TRUE, type=c("pearson", "spearman"), ...){
  77. se.r <- function(r, n){
  78. rho <- r*(1 + (1 - r^2)/(2*(n - 3))) # approx. unbiased estimator
  79. v <- (((1 - rho^2)^2)/(n + 6))*(1 + (14 + 11*rho^2)/(2*(n + 6)))
  80. sqrt(v)
  81. }
  82. use <- match.arg(use)
  83. if (class(data) != "data.frame") stop("argument must be a data frame.")
  84. if (use == "complete.obs") data <- na.omit(data)
  85. p <- length(data)
  86. if (p < 2) stop("fewer than 2 variables.")
  87. R <- matrix(1, p, p)
  88. Type <- matrix("", p, p)
  89. SE <- matrix(0, p, p)
  90. N <- matrix(0, p, p)
  91. Test <- matrix(0, p, p)
  92. diag(N) <- if (use == "complete.obs") nrow(data)
  93. else sapply(data, function(x) sum(!is.na(x)))
  94. for (i in 2:p) {
  95. print(i)
  96. for (j in 1:(i-1)){
  97. x <- data[[i]]
  98. y <- data[[j]]
  99. if (inherits(x, c("numeric", "integer")) && inherits(y, c("numeric", "integer"))) {
  100. # r <- cor(x, y, use="complete.obs")
  101. # r <- rcorr(x, y, type="pearson")$r[1,2]
  102. r <- rcorr(x, y, type=type)$r[1,2]
  103. # Type[i, j] <- Type[j, i] <- "Pearson"
  104. # Type[i, j] <- Type[j, i] <- "rcorr Pearson"
  105. if (type=="spearman")
  106. Type[i, j] <- Type[j, i] <- "rcorr Spearman"
  107. else
  108. Type[i, j] <- Type[j, i] <- "rcorr Pearson"
  109. R[i, j] <- R[j, i] <- r
  110. if (std.err) {
  111. n <- sum(complete.cases(x, y))
  112. SE[i, j] <- SE[j, i] <- se.r(r, n)
  113. N[i, j] <- N[j, i] <- n
  114. Test[i, j] <- pchisq(chisq(x, y, r, bins=bins), bins^2 - 2, lower.tail=FALSE)
  115. }
  116. }
  117. else if (inherits(x, "factor") && inherits(y, "factor")) {
  118. Type[i, j] <- Type[j, i] <- "Polychoric"
  119. result <- polychor(x, y, ML=ML, std.err=std.err)
  120. if (std.err){
  121. n <- sum(complete.cases(x, y))
  122. R[i, j] <- R[j, i] <- result$rho
  123. SE[i, j] <- SE[j, i] <- sqrt(result$var[1,1])
  124. N[i, j] <- N[j, i] <- n
  125. Test[i, j] <- if (result$df > 0)
  126. pchisq(result$chisq, result$df, lower.tail=FALSE)
  127. else NA
  128. }
  129. else R[i, j] <- R[j, i] <- result
  130. }
  131. else {
  132. if (inherits(x, "factor") && inherits(y, c("numeric", "integer")))
  133. result <- polyserial(y, x, ML=ML, std.err=std.err, bins=bins)
  134. else if (inherits(x, c("numeric", "integer")) && inherits(y, "factor"))
  135. result <- polyserial(x, y, ML=ML, std.err=std.err, bins=bins)
  136. else {
  137. stop("columns must be numeric or factors.")
  138. }
  139. Type[i, j] <- Type[j, i] <- "Polyserial"
  140. if (std.err){
  141. n <- sum(complete.cases(x, y))
  142. R[i, j] <- R[j, i] <- result$rho
  143. SE[i, j] <- SE[j, i] <- sqrt(result$var[1,1])
  144. N[i, j] <- N[j, i] <- n
  145. Test[i, j] <- pchisq(result$chisq, result$df, lower.tail=FALSE)
  146. }
  147. else R[i, j] <- R[j, i] <- result
  148. }
  149. }
  150. }
  151. if (pd) {
  152. if (min(eigen(R, only.values=TRUE)$values) < 0){
  153. cor <- nearcor(R)
  154. if (!cor$converged) stop("attempt to make correlation matrix positive-definite failed")
  155. warning("the correlation matrix has been adjusted to make it positive-definite")
  156. R <- cor$cor
  157. }
  158. }
  159. rownames(R) <- colnames(R) <- names(data)
  160. result <- list(correlations=R, type=Type, NA.method=use, ML=ML)
  161. if (std.err) {
  162. rownames(SE) <- colnames(SE) <- names(data)
  163. rownames(N) <- colnames(N) <- names(N)
  164. rownames(Test) <- colnames(Test) <- names(data)
  165. result$std.errors <- SE
  166. result$n <- if (use == "complete.obs") n else N
  167. result$tests <- Test
  168. }
  169. class(result) <- "hetcor"
  170. result
  171. }
  172. # based on heatmap.2
  173. # Changed so that labels are on a different axis, close to clustering
  174. heatmap.3 = function (x, Rowv = TRUE, Colv = if (symm) "Rowv" else TRUE,
  175. distfun = dist, hclustfun = hclust, dendrogram = c("both",
  176. "row", "column", "none"), symm = FALSE, scale = c("none",
  177. "row", "column"), na.rm = TRUE, revC = identical(Colv,
  178. "Rowv"), add.expr, breaks, symbreaks = min(x < 0, na.rm = TRUE) ||
  179. scale != "none", col = "heat.colors", colsep, rowsep,
  180. sepcolor = "white", sepwidth = c(0.05, 0.05), cellnote, notecex = 1,
  181. notecol = "cyan", na.color = par("bg"), trace = c("column",
  182. "row", "both", "none"), tracecol = "cyan", hline = median(breaks),
  183. vline = median(breaks), linecol = tracecol, margins = c(5,
  184. 5), ColSideColors, RowSideColors, cexRow = 0.2 + 1/log10(nr),
  185. cexCol = 0.2 + 1/log10(nc), labRow = NULL, labCol = NULL,
  186. key = TRUE, keysize = 1.5, density.info = c("histogram",
  187. "density", "none"), denscol = tracecol, symkey = min(x <
  188. 0, na.rm = TRUE) || symbreaks, densadj = 0.25, main = NULL,
  189. xlab = NULL, ylab = NULL, lmat = NULL, lhei = NULL, lwid = NULL,
  190. ...)
  191. {
  192. scale01 <- function(x, low = min(x), high = max(x)) {
  193. x <- (x - low)/(high - low)
  194. x
  195. }
  196. retval <- list()
  197. scale <- if (symm && missing(scale))
  198. "none"
  199. else match.arg(scale)
  200. dendrogram <- match.arg(dendrogram)
  201. trace <- match.arg(trace)
  202. density.info <- match.arg(density.info)
  203. if (length(col) == 1 && is.character(col))
  204. col <- get(col, mode = "function")
  205. if (!missing(breaks) && (scale != "none"))
  206. warning("Using scale=\"row\" or scale=\"column\" when breaks are",
  207. "specified can produce unpredictable results.", "Please consider using only one or the other.")
  208. if (is.null(Rowv) || is.na(Rowv))
  209. Rowv <- FALSE
  210. if (is.null(Colv) || is.na(Colv))
  211. Colv <- FALSE
  212. else if (Colv == "Rowv" && !isTRUE(Rowv))
  213. Colv <- FALSE
  214. if (length(di <- dim(x)) != 2 || !is.numeric(x))
  215. stop("`x' must be a numeric matrix")
  216. nr <- di[1]
  217. nc <- di[2]
  218. if (nr <= 1 || nc <= 1)
  219. stop("`x' must have at least 2 rows and 2 columns")
  220. if (!is.numeric(margins) || length(margins) != 2)
  221. stop("`margins' must be a numeric vector of length 2")
  222. if (missing(cellnote))
  223. cellnote <- matrix("", ncol = ncol(x), nrow = nrow(x))
  224. if (!inherits(Rowv, "dendrogram")) {
  225. if (((!isTRUE(Rowv)) || (is.null(Rowv))) && (dendrogram %in%
  226. c("both", "row"))) {
  227. if (is.logical(Colv) && (Colv))
  228. dendrogram <- "column"
  229. else dedrogram <- "none"
  230. warning("Discrepancy: Rowv is FALSE, while dendrogram is `",
  231. dendrogram, "'. Omitting row dendogram.")
  232. }
  233. }
  234. if (!inherits(Colv, "dendrogram")) {
  235. if (((!isTRUE(Colv)) || (is.null(Colv))) && (dendrogram %in%
  236. c("both", "column"))) {
  237. if (is.logical(Rowv) && (Rowv))
  238. dendrogram <- "row"
  239. else dendrogram <- "none"
  240. warning("Discrepancy: Colv is FALSE, while dendrogram is `",
  241. dendrogram, "'. Omitting column dendogram.")
  242. }
  243. }
  244. if (inherits(Rowv, "dendrogram")) {
  245. ddr <- Rowv
  246. rowInd <- order.dendrogram(ddr)
  247. }
  248. else if (is.integer(Rowv)) {
  249. hcr <- hclustfun(distfun(x))
  250. ddr <- as.dendrogram(hcr)
  251. ddr <- reorder(ddr, Rowv)
  252. rowInd <- order.dendrogram(ddr)
  253. if (nr != length(rowInd))
  254. stop("row dendrogram ordering gave index of wrong length")
  255. }
  256. else if (isTRUE(Rowv)) {
  257. Rowv <- rowMeans(x, na.rm = na.rm)
  258. hcr <- hclustfun(distfun(x))
  259. ddr <- as.dendrogram(hcr)
  260. ddr <- reorder(ddr, Rowv)
  261. rowInd <- order.dendrogram(ddr)
  262. if (nr != length(rowInd))
  263. stop("row dendrogram ordering gave index of wrong length")
  264. }
  265. else {
  266. rowInd <- nr:1
  267. }
  268. if (inherits(Colv, "dendrogram")) {
  269. ddc <- Colv
  270. colInd <- order.dendrogram(ddc)
  271. }
  272. else if (identical(Colv, "Rowv")) {
  273. if (nr != nc)
  274. stop("Colv = \"Rowv\" but nrow(x) != ncol(x)")
  275. if (exists("ddr")) {
  276. ddc <- ddr
  277. colInd <- order.dendrogram(ddc)
  278. }
  279. else colInd <- rowInd
  280. }
  281. else if (is.integer(Colv)) {
  282. hcc <- hclustfun(distfun(if (symm)
  283. x
  284. else t(x)))
  285. ddc <- as.dendrogram(hcc)
  286. ddc <- reorder(ddc, Colv)
  287. colInd <- order.dendrogram(ddc)
  288. if (nc != length(colInd))
  289. stop("column dendrogram ordering gave index of wrong length")
  290. }
  291. else if (isTRUE(Colv)) {
  292. Colv <- colMeans(x, na.rm = na.rm)
  293. hcc <- hclustfun(distfun(if (symm)
  294. x
  295. else t(x)))
  296. ddc <- as.dendrogram(hcc)
  297. ddc <- reorder(ddc, Colv)
  298. colInd <- order.dendrogram(ddc)
  299. if (nc != length(colInd))
  300. stop("column dendrogram ordering gave index of wrong length")
  301. }
  302. else {
  303. colInd <- 1:nc
  304. }
  305. retval$rowInd <- rowInd
  306. retval$colInd <- colInd
  307. retval$call <- match.call()
  308. x <- x[rowInd, colInd]
  309. x.unscaled <- x
  310. cellnote <- cellnote[rowInd, colInd]
  311. if (is.null(labRow))
  312. labRow <- if (is.null(rownames(x)))
  313. (1:nr)[rowInd]
  314. else rownames(x)
  315. else labRow <- labRow[rowInd]
  316. if (is.null(labCol))
  317. labCol <- if (is.null(colnames(x)))
  318. (1:nc)[colInd]
  319. else colnames(x)
  320. else labCol <- labCol[colInd]
  321. if (scale == "row") {
  322. retval$rowMeans <- rm <- rowMeans(x, na.rm = na.rm)
  323. x <- sweep(x, 1, rm)
  324. retval$rowSDs <- sx <- apply(x, 1, sd, na.rm = na.rm)
  325. x <- sweep(x, 1, sx, "/")
  326. }
  327. else if (scale == "column") {
  328. retval$colMeans <- rm <- colMeans(x, na.rm = na.rm)
  329. x <- sweep(x, 2, rm)
  330. retval$colSDs <- sx <- apply(x, 2, sd, na.rm = na.rm)
  331. x <- sweep(x, 2, sx, "/")
  332. }
  333. if (missing(breaks) || is.null(breaks) || length(breaks) <
  334. 1) {
  335. if (missing(col) || is.function(col))
  336. breaks <- 16
  337. else breaks <- length(col) + 1
  338. }
  339. if (length(breaks) == 1) {
  340. if (!symbreaks)
  341. breaks <- seq(min(x, na.rm = na.rm), max(x, na.rm = na.rm),
  342. length = breaks)
  343. else {
  344. extreme <- max(abs(x), na.rm = TRUE)
  345. breaks <- seq(-extreme, extreme, length = breaks)
  346. }
  347. }
  348. nbr <- length(breaks)
  349. ncol <- length(breaks) - 1
  350. if (class(col) == "function")
  351. col <- col(ncol)
  352. min.breaks <- min(breaks)
  353. max.breaks <- max(breaks)
  354. x[x < min.breaks] <- min.breaks
  355. x[x > max.breaks] <- max.breaks
  356. if (missing(lhei) || is.null(lhei))
  357. lhei <- c(keysize, 4)
  358. if (missing(lwid) || is.null(lwid))
  359. lwid <- c(keysize, 4)
  360. if (missing(lmat) || is.null(lmat)) {
  361. lmat <- rbind(4:3, 2:1)
  362. if (!missing(ColSideColors)) {
  363. if (!is.character(ColSideColors) || length(ColSideColors) !=
  364. nc)
  365. stop("'ColSideColors' must be a character vector of length ncol(x)")
  366. lmat <- rbind(lmat[1, ] + 1, c(NA, 1), lmat[2, ] +
  367. 1)
  368. lhei <- c(lhei[1], 0.2, lhei[2])
  369. }
  370. if (!missing(RowSideColors)) {
  371. if (!is.character(RowSideColors) || length(RowSideColors) !=
  372. nr)
  373. stop("'RowSideColors' must be a character vector of length nrow(x)")
  374. lmat <- cbind(lmat[, 1] + 1, c(rep(NA, nrow(lmat) -
  375. 1), 1), lmat[, 2] + 1)
  376. lwid <- c(lwid[1], 0.2, lwid[2])
  377. }
  378. lmat[is.na(lmat)] <- 0
  379. }
  380. if (length(lhei) != nrow(lmat))
  381. stop("lhei must have length = nrow(lmat) = ", nrow(lmat))
  382. if (length(lwid) != ncol(lmat))
  383. stop("lwid must have length = ncol(lmat) =", ncol(lmat))
  384. op <- par(no.readonly = TRUE)
  385. on.exit(par(op))
  386. layout(lmat, widths = lwid, heights = lhei, respect = FALSE)
  387. if (!missing(RowSideColors)) {
  388. par(mar = c(margins[1], 0, 0, 0.5))
  389. image(rbind(1:nr), col = RowSideColors[rowInd], axes = FALSE)
  390. }
  391. if (!missing(ColSideColors)) {
  392. par(mar = c(0.5, 0, 0, margins[2]))
  393. image(cbind(1:nc), col = ColSideColors[colInd], axes = FALSE)
  394. }
  395. par(mar = c(margins[1], 0, 0, margins[2]))
  396. x <- t(x)
  397. cellnote <- t(cellnote)
  398. if (revC) {
  399. iy <- nr:1
  400. if (exists("ddr"))
  401. ddr <- rev(ddr)
  402. x <- x[, iy]
  403. cellnote <- cellnote[, iy]
  404. }
  405. else iy <- 1:nr
  406. image(1:nc, 1:nr, x, xlim = 0.5 + c(0, nc), ylim = 0.5 +
  407. c(0, nr), axes = FALSE, xlab = "", ylab = "", col = col,
  408. breaks = breaks, ...)
  409. retval$carpet <- x
  410. if (exists("ddr"))
  411. retval$rowDendrogram <- ddr
  412. if (exists("ddc"))
  413. retval$colDendrogram <- ddc
  414. retval$breaks <- breaks
  415. retval$col <- col
  416. if (!invalid(na.color) & any(is.na(x))) {
  417. mmat <- ifelse(is.na(x), 1, NA)
  418. image(1:nc, 1:nr, mmat, axes = FALSE, xlab = "", ylab = "",
  419. col = na.color, add = TRUE)
  420. }
  421. axis(1, 1:nc, labels = labCol, las = 2, line = -0.5, tick = 0,
  422. cex.axis = cexCol)
  423. # Also put them on the other side
  424. axis(3, 1:nc, labels = labCol, las = 2, line = -0.5, tick = 0,
  425. cex.axis = cexCol)
  426. if (!is.null(xlab))
  427. mtext(xlab, side = 1, line = margins[1] - 1.25)
  428. if (!is.null(xlab))
  429. mtext(xlab, side = 3, line = margins[1] - 1.25)
  430. # Also put them on the top axis
  431. axis(2, iy, labels = labRow, las = 2, line = -0.5, tick = 0,
  432. cex.axis = cexRow)
  433. axis(4, iy, labels = labRow, las = 2, line = -0.5, tick = 0,
  434. cex.axis = cexRow)
  435. if (!is.null(ylab))
  436. mtext(ylab, side = 2, line = margins[2] - 1.25)
  437. if (!is.null(ylab))
  438. mtext(ylab, side = 4, line = margins[2] - 1.25)
  439. if (!missing(add.expr))
  440. eval(substitute(add.expr))
  441. if (!missing(colsep))
  442. for (csep in colsep) rect(xleft = csep + 0.5, ybottom = rep(0,
  443. length(csep)), xright = csep + 0.5 + sepwidth[1],
  444. ytop = rep(ncol(x) + 1, csep), lty = 1, lwd = 1,
  445. col = sepcolor, border = sepcolor)
  446. if (!missing(rowsep))
  447. for (rsep in rowsep) rect(xleft = 0, ybottom = (ncol(x) +
  448. 1 - rsep) - 0.5, xright = nrow(x) + 1, ytop = (ncol(x) +
  449. 1 - rsep) - 0.5 - sepwidth[2], lty = 1, lwd = 1,
  450. col = sepcolor, border = sepcolor)
  451. min.scale <- min(breaks)
  452. max.scale <- max(breaks)
  453. x.scaled <- scale01(t(x), min.scale, max.scale)
  454. if (trace %in% c("both", "column")) {
  455. retval$vline <- vline
  456. vline.vals <- scale01(vline, min.scale, max.scale)
  457. for (i in colInd) {
  458. if (!is.null(vline)) {
  459. abline(v = i - 0.5 + vline.vals, col = linecol,
  460. lty = 2)
  461. }
  462. xv <- rep(i, nrow(x.scaled)) + x.scaled[, i] - 0.5
  463. xv <- c(xv[1], xv)
  464. yv <- 1:length(xv) - 0.5
  465. lines(x = xv, y = yv, lwd = 1, col = tracecol, type = "s")
  466. }
  467. }
  468. if (trace %in% c("both", "row")) {
  469. retval$hline <- hline
  470. hline.vals <- scale01(hline, min.scale, max.scale)
  471. for (i in rowInd) {
  472. if (!is.null(hline)) {
  473. abline(h = i + hline, col = linecol, lty = 2)
  474. }
  475. yv <- rep(i, ncol(x.scaled)) + x.scaled[i, ] - 0.5
  476. yv <- rev(c(yv[1], yv))
  477. xv <- length(yv):1 - 0.5
  478. lines(x = xv, y = yv, lwd = 1, col = tracecol, type = "s")
  479. }
  480. }
  481. if (!missing(cellnote))
  482. text(x = c(row(cellnote)), y = c(col(cellnote)), labels = c(cellnote),
  483. col = notecol, cex = notecex)
  484. par(mar = c(margins[1], 0, 0, 0))
  485. if (dendrogram %in% c("both", "row")) {
  486. plot(ddr, horiz = TRUE, axes = FALSE, yaxs = "i", leaflab = "none")
  487. }
  488. else plot.new()
  489. par(mar = c(0, 0, if (!is.null(main)) 5 else 0, margins[2]))
  490. if (dendrogram %in% c("both", "column")) {
  491. plot(ddc, axes = FALSE, xaxs = "i", leaflab = "none")
  492. }
  493. else plot.new()
  494. if (!is.null(main))
  495. title(main, cex.main = 1.5 * op[["cex.main"]])
  496. if (key) {
  497. par(mar = c(5, 4, 2, 1), cex = 0.75)
  498. tmpbreaks <- breaks
  499. if (symkey) {
  500. max.raw <- max(abs(c(x, breaks)), na.rm = TRUE)
  501. min.raw <- -max.raw
  502. tmpbreaks[1] <- -max(abs(x))
  503. tmpbreaks[length(tmpbreaks)] <- max(abs(x))
  504. }
  505. else {
  506. min.raw <- min(x, na.rm = TRUE)
  507. max.raw <- max(x, na.rm = TRUE)
  508. }
  509. z <- seq(min.raw, max.raw, length = length(col))
  510. image(z = matrix(z, ncol = 1), col = col, breaks = tmpbreaks,
  511. xaxt = "n", yaxt = "n")
  512. par(usr = c(0, 1, 0, 1))
  513. lv <- pretty(breaks)
  514. xv <- scale01(as.numeric(lv), min.raw, max.raw)
  515. axis(1, at = xv, labels = lv)
  516. if (scale == "row")
  517. mtext(side = 1, "Row Z-Score", line = 2)
  518. else if (scale == "column")
  519. mtext(side = 1, "Column Z-Score", line = 2)
  520. else mtext(side = 1, "Value", line = 2)
  521. if (density.info == "density") {
  522. dens <- density(x, adjust = densadj, na.rm = TRUE)
  523. omit <- dens$x < min(breaks) | dens$x > max(breaks)
  524. dens$x <- dens$x[-omit]
  525. dens$y <- dens$y[-omit]
  526. dens$x <- scale01(dens$x, min.raw, max.raw)
  527. lines(dens$x, dens$y/max(dens$y) * 0.95, col = denscol,
  528. lwd = 1)
  529. axis(2, at = pretty(dens$y)/max(dens$y) * 0.95, pretty(dens$y))
  530. title("Color Key\nand Density Plot")
  531. par(cex = 0.5)
  532. mtext(side = 2, "Density", line = 2)
  533. }
  534. else if (density.info == "histogram") {
  535. h <- hist(x, plot = FALSE, breaks = breaks)
  536. hx <- scale01(breaks, min.raw, max.raw)
  537. hy <- c(h$counts, h$counts[length(h$counts)])
  538. lines(hx, hy/max(hy) * 0.95, lwd = 1, type = "s",
  539. col = denscol)
  540. axis(2, at = pretty(hy)/max(hy) * 0.95, pretty(hy))
  541. title("Color Key\nand Histogram")
  542. par(cex = 0.5)
  543. mtext(side = 2, "Count", line = 2)
  544. }
  545. else title("Color Key")
  546. }
  547. else plot.new()
  548. retval$colorTable <- data.frame(low = retval$breaks[-length(retval$breaks)],
  549. high = retval$breaks[-1], color = retval$col)
  550. invisible(retval)
  551. }