dplyr - R add values to diagonal - Stack Overflow

I want to change the diagonal elements of my data frame: in particular, for each column, I want to sum

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
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745283948a4620447.html

相关推荐

  • dplyr - R add values to diagonal - Stack Overflow

    I want to change the diagonal elements of my data frame: in particular, for each column, I want to sum

    16小时前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信