Feeds:
Posts
Comments

Posts Tagged ‘gsub’

I need to change some words in a vector, but I do not want to use gsub as I have a vector of ‘patterns’ to change which would require a loop. I have come up with the piece of code below.

The first step is to create a test dataset:

test <- c("War", "Freedom", "Ignorance")
test <- cbind(rep(test, 2), rep("is"), rep(test, 2))

test
#      [,1]        [,2] [,3]
# [1,] "War"       "is" "War"
# [2,] "Freedom"   "is" "Freedom"
# [3,] "Ignorance" "is" "Ignorance"
# [4,] "War"       "is" "War"
# [5,] "Freedom"   "is" "Freedom"
# [6,] "Ignorance" "is" "Ignorance"

A matrix with the different strings to look for and the replacement text is created.

str12 <- data.frame(
str1 = c("War", "Freedom", "Ignorance"),
str2 = c("Peace", "Slavery", "Strength"))

The function is applied to the test dataset.

test[,3] <- sapply(test[, 3], function(x){
as.character(str12$str2[match(x, str12$str1)])
})

The result is:

test
     [,1]        [,2] [,3]      
[1,] "War"       "is" "Peace"   
[2,] "Freedom"   "is" "Slavery" 
[3,] "Ignorance" "is" "Strength"
[4,] "War"       "is" "Peace"   
[5,] "Freedom"   "is" "Slavery" 
[6,] "Ignorance" "is" "Strength"

Read Full Post »