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(.)))
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
}
matrix
object:mat <- as.matrix(df)
, and then usediag(mat) <- ...
– Maël Commented Jan 29 at 18:42