You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中提取矩阵/数据框的对角元素

Extract Diagonal Elements from Your Data Frame in R

First, let's start by recreating your data frame using the dput output you provided:

df <- 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")

Extract the Anti-Diagonal (Top-Right to Bottom-Left)

Looking at your data structure, it forms an upper triangular-like matrix where the most meaningful diagonal elements run from the top-right to bottom-left (e.g., 7 from row1/X10, 6 from row2/X9, ..., 56 from row10/X1). Here's how to extract these:

# Calculate the column index for each row's diagonal element
anti_diagonal <- sapply(1:nrow(df), function(i) {
  # For row i, the diagonal column is total columns minus row index plus 1
  col_index <- ncol(df) - i + 1
  df[i, col_index]
})

# Convert to numeric (since some columns are stored as characters)
anti_diagonal <- as.numeric(anti_diagonal)

# View the result
anti_diagonal

Output:

[1]  7  6 23 12 27 78 24 27 45 56

Extract the Main Diagonal (Top-Left to Bottom-Right)

If instead you want the diagonal running from top-left to bottom-right (starting from 1 in row1/X1, 56 in row2/X2, etc.), use this code:

# Calculate the column index for each row's main diagonal element
main_diagonal <- sapply(1:nrow(df), function(i) {
  # For row i, the diagonal column is row index plus 1 (skipping the first 'X' column)
  col_index <- i + 1
  # Return NA if the column index exceeds the number of columns
  if (col_index > ncol(df)) NA else df[i, col_index]
})

# Convert to numeric
main_diagonal <- as.numeric(main_diagonal)

# View the result
main_diagonal

Output:

[1]  1 56 23 26 68 NA NA NA NA NA

Notes:

  • The anti-diagonal extraction gives you all non-empty values since it aligns with the filled elements in each row.
  • We convert the result to numeric because some columns in your data frame are stored as character strings (due to empty spaces in later rows).

内容的提问来源于stack exchange,提问作者Naive_Natural2511

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:53:43