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

时间:2014-06-24 12:32:45

标签: r

我的输入矩阵

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

在这里,我想用&#34; A&#34;,&#34; B&#34;,&#34; C&#34;,&#34; D&#34;通过遵循4字母差异的模式。即&#34; A&#34;应该替换字母&#34; a&#34;,&#34; e&#34;,&#34; i&#34;,&#34; m&#34;,&#34; q&#34;,&# 34;你&#34;,&#34; y&#34;,&#34; B&#34;替换&#34; b&#34;,&#34; f&#34;,&#34; j&#34;,....等。

我试过

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

这是不正确的。

2 个答案:

答案 0 :(得分:3)

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

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"

答案 1 :(得分:2)

使用简单的for - 循环:

for(i in 1:4) m1[m1 %in% letters[seq(i,26,by=4)]] <- LETTERS[i]

> 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"