用stringr里面的函数str_replace()配合apply实现。
library(stringr)
temp <- apply(temp, 2, function(x){str_replace(x, "aaa", "bbb")})
示例:
> temp <- matrix(rep(c("aaa", "bbb", "ccc", "ddd"),6), nrow=6, ncol=4)
> temp
[,1] [,2] [,3] [,4]
[1,] "aaa" "ccc" "aaa" "ccc"
[2,] "bbb" "ddd" "bbb" "ddd"
[3,] "ccc" "aaa" "ccc" "aaa"
[4,] "ddd" "bbb" "ddd" "bbb"
[5,] "aaa" "ccc" "aaa" "ccc"
[6,] "bbb" "ddd" "bbb" "ddd"
> temp <- apply(temp, 2, function(x){str_replace(x, "aaa", "000")})
> temp
[,1] [,2] [,3] [,4]
[1,] "000" "ccc" "000" "ccc"
[2,] "bbb" "ddd" "bbb" "ddd"
[3,] "ccc" "000" "ccc" "000"
[4,] "ddd" "bbb" "ddd" "bbb"
[5,] "000" "ccc" "000" "ccc"
[6,] "bbb" "ddd" "bbb" "ddd"
如果apply的参数改为1的话,得到的矩阵将被转置。
在生成temp矩阵的初始值后,再次应用apply函数:
> temp <- apply(temp, 1, function(x){str_replace(x, "aaa", "000")})
> temp
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "000" "bbb" "ccc" "ddd" "000" "bbb"
[2,] "ccc" "ddd" "000" "bbb" "ccc" "ddd"
[3,] "000" "bbb" "ccc" "ddd" "000" "bbb"
[4,] "ccc" "ddd" "000" "bbb" "ccc" "ddd"