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
|
1 Answer
Reset to default 0As 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
matrix
object:mat <- as.matrix(df)
, and then usediag(mat) <- ...
– Maël Commented Jan 29 at 18:42