简体   繁体   中英

How to fix “Factor level duplicated” Error in R heatmaply()?

I'm trying to make a heatmap based on that matrix:

  1     2     3     4     5     6     7
C  6211  7608  8089 10514  7363  5375  7268
L  2459  2904  2573  3049  2221  1652  2311
N  3173  4213  3025  4324  2864  1524  2363
S    37    74   141    94    68    48    88
W  1223  1259   914  1691   874   607   912

I made it by:

c1 <- table(kat_data$delay_code, kat_data$DayOfWeek)
c1 <- as.matrix(c1)
c1

And now I'm trying to make a heatmap using heatmaply() , but I got an error:

Error in levels<-( tmp `, value = as.character(levels)): factor level [6] is duplicated

Part of the heatmap code below:

p<-heatmaply(c1, 
             dendogram = "none", 
             xlab = "", ylab = "", 
             main = "",
             scale = "column", 
             margins =c(60,100,40,20),............

What should I do to make it work? I read a lot of questions with that error and I see that I need to provide unique data, but I don't know where and how to do this. Could you please help me?

We can convert it to data.frame and the error would go away as it is a case of duplicated row names which are not allowed in data.frame

library(heatmaply)
heatmaply(as.data.frame.matrix(table(mtcars[c('cyl', 'vs')])))

在此处输入图像描述

Also, to mention that by wrapping with as.matrix , the table class still remains

m1 <- as.matrix(table(mtcars[c('cyl', 'vs')]))
str(m1)
# 'table' int [1:3, 1:2] 1 3 14 10 4 0
# - attr(*, "dimnames")=List of 2
#  ..$ cyl: chr [1:3] "4" "6" "8"
#  ..$ vs : chr [1:2] "0" "1"

and that is creating the issue as the ?heatmaply suggests the 'x' to be

x- can either be a heatmapr object, or a numeric matrix Defaults to TRUE unless x contains any NAs.

So, we can convert the class to matrix

class(m1) <- "matrix"

Now, it should work

heatmaply(m1)

Note that, either the table or matrix object can result in a similar error as in the OP's post

heatmaply(table(mtcars[c('cyl', 'vs')]))

Error in levels<- ( *tmp* , value = as.character(levels)): factor level [4] is duplicated

heatmaply(as.matrix(table(mtcars[c('cyl', 'vs')])))

Error in levels<- ( *tmp* , value = as.character(levels)): factor level [4] is duplicated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM