gpt4 book ai didi

用固定值替换非对角线元素

转载 作者:行者123 更新时间:2023-12-05 08:19:24 24 4
gpt4 key购买 nike

我有一个方阵,现在我想用一个固定值替换它所有的非对角线元素。 Replacing non-diagonal elements in a matrix in R (hopefully a better asked this time) 中讨论了如何完成此操作的一些方法。

例如,

m <- matrix(c(1,2,3,4,3,9,5,5,8),ncol=3)
m[upper.tri(m) | lower.tri(m)] <- 999
m

我想知道是否可以使用dplyr 链规则 来执行该步骤,例如

library(dplyr)
matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
### add this -> m[upper.tri(m) | lower.tri(m)] <- 999

任何指针都会非常有帮助

最佳答案

如果为了简洁起见,您可以像这样在管道中定义+应用匿名函数:

matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
(\(.) {.[upper.tri(.) | lower.tri(.)] = 999; .})() %>%
## rest of pipeline

编辑无耻地窃取 @Maël 的优雅解决方案:

matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
ifelse(row(.) == col(.), ., 999) %>%
## rest of pipeline

(注意:不适用于 native 管道运算符 |>)

关于用固定值替换非对角线元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74918962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com