gpt4 book ai didi

r - 使用模式更改矩阵中的多个值

转载 作者:行者123 更新时间:2023-12-02 09:37:12 25 4
gpt4 key购买 nike

我的输入矩阵

set.seed(123)
m1 <- matrix(sample(letters, 50, replace=TRUE), 5)

在这里,我想按照 4 个字母差异的模式将字母替换为“A”、“B”、“C”、“D”。即“A”应替换字母“a”,“e”,“i”,“m”,“q”,“u”,“y”,“B”替换“b”,“f”,“j” ,....ETC。

我试过了

replace(m1, c("a","e","i","m","q", "u", "y"), "A")

这是不正确的。

最佳答案

这是一种使用模运算的方法:

matrix(toupper(letters)[((match(m1, letters) - 1) %% 4) + 1], ncol=ncol(m1))

# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] "D" "B" "A" "D" "D" "C" "B" "A" "D" "D"
# [2,] "A" "B" "D" "C" "C" "C" "D" "D" "C" "C"
# [3,] "C" "D" "B" "B" "A" "D" "B" "B" "C" "A"
# [4,] "C" "C" "C" "A" "B" "D" "A" "A" "B" "C"
# [5,] "A" "D" "C" "A" "B" "D" "A" "C" "D" "C"

关于r - 使用模式更改矩阵中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24386745/

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