簡體   English   中英

按組復制第一行中數據框/矩陣的對角線

[英]Copying the diagonal of a dataframe/matrix in the first row, by group

假設我有以下矩陣mat3 ,其中第 1 列是定義 2 個組的變量:

mat1 <- diag(1, 5, 5)
mat1[,1] <- 1
mat2 <- diag(3, 5, 5)
mat2[,1] <- 3
mat3 <- rbind(mat1, mat2)
mat3

mat3中,如何將mat1mat2的對角線復制到它們各自的第一行(即第 1 行和第 6 行)? 偽代碼將是: diag(mat3) by mat3[,1]

我嘗試了以下但沒有奏效:

fnc <- function(x) {
  res <- x
  res[1,] <- diag(x)
  res <<- res
}

by(mat3, as.factor(mat3[,1]), fnc)
res

在實踐中,我需要將此操作應用於 dataframe。

非常感謝!

do.call(rbind, lapply(split.data.frame(mat3, mat3[,1]), \(x) {
  x[1, ] <- diag(x); x
}))

      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    1    1    1    1
 [2,]    1    1    0    0    0
 [3,]    1    0    1    0    0
 [4,]    1    0    0    1    0
 [5,]    1    0    0    0    1
 [6,]    3    3    3    3    3
 [7,]    3    3    0    0    0
 [8,]    3    0    3    0    0
 [9,]    3    0    0    3    0
[10,]    3    0    0    0    3

如果mat3data.frame ,您可以將匿名 function 修改為

\(x) {
  x[1, ] <- diag(as.matrix(x)); x
}

這是一個假設它們是正方形的假設它們是正方形的方法,它只是找到每個矩陣的開始:

idx <- seq(from=1, to=nrow(mat3), by=ncol(mat3))
for(i in idx) mat3[i, ] <- rep(mat3[i, 1], ncol(mat3))
mat3
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    1    1    1    1    1
#  [2,]    1    1    0    0    0
#  [3,]    1    0    1    0    0
#  [4,]    1    0    0    1    0
#  [5,]    1    0    0    0    1
#  [6,]    3    3    3    3    3
#  [7,]    3    3    0    0    0
#  [8,]    3    0    3    0    0
#  [9,]    3    0    0    3    0
# [10,]    3    0    0    0    3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM