I want to create a matrix/vector from csv and xlsx files without titles at rows and columns. Also, I want to create a diagonal vector ( similar to diag (X) command in MATLAB) from xlsx file without title cell value. I would be glad if anyone helps me with the syntax for these purposes.
The following illustrates the xlsx file from which I want to create matrix and vector.
Here is a simple example of importing a csv with row and column names and converting it to a matrix and also making a diagonal matrix.
df <- read.csv("C:\\Users\\fjcc\\Documents\\R\\Play\\Dummy.txt")
df
#> A B C
#> row1 10 11 12
#> row2 20 21 22
#> row3 30 31 32
MAT <- as.matrix(df)
MAT
#> A B C
#> row1 10 11 12
#> row2 20 21 22
#> row3 30 31 32
dimnames(MAT) <- list(NULL, NULL) #if you do not want the names
MAT
#> [,1] [,2] [,3]
#> [1,] 10 11 12
#> [2,] 20 21 22
#> [3,] 30 31 32
DiagMat <- diag(MAT[, 1]) #make a diagonal matrix from the first column of MAT
DiagMat
#> [,1] [,2] [,3]
#> [1,] 10 0 0
#> [2,] 0 20 0
#> [3,] 0 0 30
Created on 2019-02-28 by the reprex package (v0.2.1)
1 Like
Hey FJCC,
I am glad you replied. However, it doesn't work since my xlsx file contains multiple sheets. how to define sheet for read.csv function? Thank you
1 Like
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.