简体   繁体   中英

How to obtain diagonal elements of the matrix in R

I have a dataset as attached herewith.

数据集

I want to extract diagonal elements from this matrix. The output should look like below. How do I go about it using R?

输出量

Please find the link to the excel file.

https://1drv.ms/x/s!AmU_Vk1czmwRgWFvnMYsga56vVMb

Output of dput(df):

 X X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 1 11 1 12 4 46 78 45 89 45 45 7 2 12 2 56 5 12 12 23 566 26 6 3 13 3 23 23 28 24 28 23 23 4 14 4 45 12 26 46 24 12 5 15 5 89 56 24 68 27 6 16 6 23 26 26 78 7 17 8 23 24 24 8 18 9 12 27 9 19 12 45 10 20 56 structure(list(X = 11:20, X1 = c(1L, 2L, 3L, 4L, 5L, 6L, 8L, 9L, 12L, 56L), X2 = c("12", "56", "23", "45", "89", "23", "23", "12", "45", " "), X3 = c("4", "5", "23", "12", "56", "26", "24", "27", " ", " "), X4 = c("46", "12", "28", "26", "24", "26", "24", " ", " ", " "), X5 = c("78", "12", "24", "46", "68", "78", " ", " ", " ", " "), X6 = c("45", "23", "28", "24", "27", " ", " ", " ", " ", " "), X7 = c("89", "566", "23", "12", " ", " ", " ", " ", " ", " "), X8 = c("45", "26", "23", " ", " ", " ", " ", " ", " ", " "), X9 = c("45", "6", " ", " ", " ", " ", " ", " ", " ", " "), X10 = c("7", " ", " ", " ", " ", " ", " ", " ", " ", " ")), row.names = c(NA, -10L), class = "data.frame") 

I would reverse the order of the columns - then you can convert it to a matrix and take the diagonal easily:

df[ncol(df):1] %>% 
  as.matrix() %>% 
  diag()

or equivalently if you're not familiar with the pipe operator ( %>% ):

diag(as.matrix(df[ncol(df):1]))

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