用stringr里面的函數(shù)str_replace()配合apply實(shí)現(xiàn)。
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的參數(shù)改為1的話瑞眼,得到的矩陣將被轉(zhuǎn)置敷鸦。
在生成temp矩陣的初始值后东亦,再次應(yīng)用apply函數(shù):
> 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"