length of 'dimnames' [2] not equal to array extent when using corrplot function from a matrix read from a csv file
Asked Answered
R

1

8

I wanna read the data from a csv file, save it as a matrix and use it for visualization.

data<-read.table("Desktop/Decision_Tree/cor_test_.csv",header = F,sep = ",")

data
V1    V2    V3   V4  V5     V6
1  1.00  0.00  0.00 0.00  0.00  0
2  0.11  1.00  0.00 0.00  0.00  0
3  0.12  0.03  1.00 0.00  0.00  0
4 -0.04  0.54  0.32 1.00  0.00  0
5 -0.12  0.57 -0.09 0.26  1.00  0
6  0.21 -0.04  0.24 0.18 -0.21  1

It goes well. But then:

corrplot(data, method = 'color', addCoef.col="grey")

It is said that:

Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr, : length of 'dimnames' [2] not equal to array extent

I don't know how to solve it.

Rotl answered 12/4, 2017 at 6:55 Comment(0)
P
12

corrplot requires a matrix, I assume your data is a data frame. Use as.matrix(data) instead.

Example:

## Your data as data frame:
data <- structure(list(V1 = c(1, 0.11, 0.12, -0.04, -0.12, 0.21), V2 = c(0, 
                    1, 0.03, 0.54, 0.57, -0.04), V3 = c(0, 0, 1, 0.32, -0.09, 0.24
                ), V4 = c(0, 0, 0, 1, 0.26, 0.18), V5 = c(0, 0, 0, 0, 1, -0.21
                ), V6 = c(0, 0, 0, 0, 0, 1)), .Names = c("V1", "V2", "V3", "V4", 
                "V5", "V6"), row.names = c(NA, -6L), class = "data.frame")

## Using the data frame results in an error:
corrplot::corrplot(data, method = 'color', addCoef.col = "grey")
# Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr,  : 
#   length of 'dimnames' [2] not equal to array extent

## Using the matrix works:
corrplot::corrplot(as.matrix(data), method = 'color', addCoef.col = "grey")

corrplot

Poacher answered 12/4, 2017 at 7:46 Comment(4)
Reeeeeally appreciate for the solution. It works perfectly. Thx a lot.Rotl
I adapted the code from the above post and ran it based on my data. But I got an error like this: "The matrix is not in [-1, 1]!"Nissy
You need to convert your data to a correlation matrix first, e.g. with cor(df). (sorry, comment probably far too late to help you @XianZhao , but leaving in case it helps someone else).Homey
Thanks, @HomeyNissy

© 2022 - 2024 — McMap. All rights reserved.