【问题标题】:Is there another way to write the following function without the for loop in R?是否有另一种方法可以在 R 中不使用 for 循环来编写以下函数?
【发布时间】:2020-02-21 23:55:45
【问题描述】:

我正在尝试编写没有 for 循环的以下函数。请注意,我正在尝试复制函数diag()

selfdiag <- function(a) {
  j <- c()
  for (i in 1:ncol(a)) {
    j[i] <- a[i, i]
  }
  return(j)
}

考虑一下:

mat <- matrix(rnorm(4), ncol = 2)

函数selfdiag() 应该创建与diag() 相同的结果。 感谢您对此的任何帮助。

【问题讨论】:

  • mat[row(mat)==col(mat)]

标签: r function for-loop


【解决方案1】:

您可以使用对角线的行和列索引创建一个数据框,并使用它从矩阵中提取对角线值。

mat <- matrix(rnorm(4), ncol = 2)

diag() 的实现方式 -

diag(mat)
[1] -0.5004046 -0.8785558

另一种方法-

rows_cols <- data.frame(rows = c(1:ncol(mat)), cols = c(1:ncol(mat)))
mat2 <- mat[as.matrix(rows_cols)]
mat2
[1] -0.5004046 -0.8785558

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多