Heatmap returning error: 'x' must be a numeric matrix, but x is a numeric matrix

Heatmap returning error: 'x' must be a numeric matrix, but x is a numeric matrix

我正在尝试创建六个地点的物种丰度热图。 我有一个站点与物种矩阵,包含数值丰度数据。

然而,当我 运行 我的代码时,R returns 一个错误,我的矩阵是非数字的。 谁能弄清楚这个?我被难住了。

导出的数据帧link:log_mean_wide

工作:

lrc <- rainbow(nrow(log_mean_wide), start = 0, end = .3)
lcc <- rainbow(ncol(log_mean_wide), start = 0, end = .3)


logmap <- heatmap(log_mean_wide, col = cm.colors(256), scale = "column", 
               RowSideColors = lrc, ColSideColors = lcc, margins = c(5, 10),
               xlab = "species", ylab = "Site", 
               main = "heatmap(<Auckland Council MCI data 1999, habitat:bank>, ..., scale = \"column\")")

error message: Error in heatmap(log_mean_wide, Rowv = NA, Colv = NA, col = cm.colors(256), : 'x' must be a numeric matrix

log_heatmap <- heatmap(log_mean_wide, Rowv=NA, Colv=NA, col = cm.colors(256), scale="column", margins=c(5,10)) #same error

is.numeric(log_mean_wide) #[1] FALSE
is.character(log_mean_wide) #[1] FALSE
is.factor(log_mean_wide) #[1] FALSE
is.logical(log_mean_wide) #[1] FALSE
is.integer(log_mean_wide) #[1] FALSE

?!?!

dims <- dim(log_mean_wide)
log_mean_matrix <- as.numeric(log_mean_wide) 
dim(log_mean_matrix) <- dims

Error: (list) object cannot be coerced to type 'double'

str(log_mean_wide) 将物种显示为数字,将站点显示为字符 - 为什么这不起作用?

storage.mode(log_mean_wide) <- "numeric" 

Error in storage.mode(log_mean_wide) <- "numeric" : (list) object cannot be coerced to type 'double'

有两个问题:

  1. 第一列 log_mean_wide$Site 是非数字。
  2. heatmap 只接受 matrix 作为输入数据(不是 data.frame)。

要解决这些问题,您可以执行以下操作(请注意,热图中有 很多 混乱):

# Store Site information as rownames
df <- log_mean_wide;
rownames(df) <- log_mean_wide[, 1];

# Remove non-numeric column
df <- df[, -1];

# Use as.matrix to convert data.frame to matrix
logmap <- heatmap(
    as.matrix(df),
    col = cm.colors(256),
    scale = "column",
    margins = c(5, 10),
    xlab = "species", ylab = "Site",
    main = "heatmap(<Auckland Council MCI data 1999, habitat:bank>, ..., scale = \"column\")")

这是一个老问题,但由于我花了一些时间弄清楚问题是什么,所以我会在这里添加一个答案。绘制一个heatmap,如果注释数据是一个tibble.

,具体添加注释列可能会失败

可重现的例子:

test = matrix(rnorm(200), 20, 10)
test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4
colnames(test) = paste("Test", 1:10, sep = "")
rownames(test) = paste("Gene", 1:20, sep = "")
annotation_col = data.frame(
  CellType = factor(rep(c("CT1", "CT2"), 5)), 
  Time = 1:5
)
rownames(annotation_col) = paste("Test", 1:10, sep = "")
pheatmap::pheatmap(test, annotation_col = 
                     annotation_col)

以上作品。但是,如果您改为使用 tibble,则会出现错误

pheatmap::pheatmap(test, annotation_col = 
                     dplyr::as_tibble(annotation_col))

Error in cut.default(a, breaks = 100) : 'x' must be numeric

注意

我认为这个错误最好指定我们需要 data.frame 而不是其他东西。这可能更具体。

请参阅 this 问题。