dplyr - R add values to diagonal - Stack Overflow

admin2025-04-22  0

I want to change the diagonal elements of my data frame: in particular, for each column, I want to sum the values of the entire column, then add that number to the diagonal entry of the column, and repeat the procedure for the diagonal entry of each column.

I've tried to no avail

 df %>% replace(col(.) == row(.), sum(col(.))) 

I want to change the diagonal elements of my data frame: in particular, for each column, I want to sum the values of the entire column, then add that number to the diagonal entry of the column, and repeat the procedure for the diagonal entry of each column.

I've tried to no avail

 df %>% replace(col(.) == row(.), sum(col(.))) 
Share Improve this question asked Jan 29 at 18:38 YvanYvan 234 bronze badges 1
  • 8 You would be better off with a matrix object: mat <- as.matrix(df), and then use diag(mat) <- ... – Maël Commented Jan 29 at 18:42
Add a comment  | 

1 Answer 1

Reset to default 0

As the comment notes, this is much easier to deal with as a matrix,

add_sum_to_diagonal = function(df) {
  x = as.matrix(df)
  diag(x) = diag(x) + colSums(x)
  df[] = x
  df
}
cars %>% add_sum_to_diagonal() %>% head

If you are desperate to remain as a data.frame, you could

add_sum_to_diagonal_alt = function(df) {
  df[] = purrr::map2(df, seq_along(df), ~{
    .x[.y] = sum(.x)
    .x
  })
  df
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745283949a294275.html

最新回复(0)