crock1255
crock1255

Reputation: 1085

Recode multiple responses into one in R

I want to search for anything that has a "3" in it, and replace it with "3D". I played around with gsub and stringr, but don't seem to be able to get the regexes correct. Any help would be great! I've been spending way too long on this.

type_3d <- as.matrix(c("3D","3D","3D Column","3D Plot","3D Scatter","3D Plot","3D   Scatter","3d Column"))

Upvotes: 1

Views: 260

Answers (2)

John
John

Reputation: 23758

Andrie has a good answer for your question.

While what you're looking for can solve a specific problem, the general problem of finding all of these kinds of messy things in your data is rather tedious in R. There are tools designed specifically for doing that though. You might want to look at Google Refine.

Upvotes: 1

Andrie
Andrie

Reputation: 179418

I'm not sure I understand you correctly, since this what you describe is a really simple use of gsub:

gsub("3", "3D", type_3d)
     [,1]         
[1,] "3DD"        
[2,] "3DD"        
[3,] "3DD Column" 
[4,] "3DD Plot"   
[5,] "3DD Scatter"
[6,] "3DD Plot"   
[7,] "3DD Scatter"
[8,] "3Dd Column" 

Or perhaps you meant:

> gsub(".*3.*", "3D", c(type_3d, "Some other text without a three"))
[1] "3D"                              "3D"                             
[3] "3D"                              "3D"                             
[5] "3D"                              "3D"                             
[7] "3D"                              "3D"                             
[9] "Some other text without a three"

Upvotes: 2

Related Questions