SparkUser
SparkUser

Reputation: 157

How to replace a variable containing a string by the string itself?

I have a variable with lots of value, one of its value is like 'Blamo BSM258 Clem on/o' and i want to replace it by 'BSM'. In some words, I want to replace with 'BSM' every value of my variable containing 'BSM'.

I've tried using

  sub("(BSM)", "BSM", data$variable)

or

  data$variable[grep("(BSM)", data$variable)]<-"BSM"

but it doesn't work. (it makes 'NA' values)

Upvotes: 1

Views: 63

Answers (2)

Colin Robinson
Colin Robinson

Reputation: 144

Using sub or gsub only replaces the patterns in the string, so you are just replacing "BSM" with "BSM" not the whole string. But the second example, with grep should work. If you are looking for "BSM" in the string, you do not need the parenthesis around it in the grep command, just pass data$variable[grep("BSM", data$variable)]<-"BSM" and everything should be done properly.

What is the structure of data? Is it a list or a dataframe? If it is a list, then the $ might not be properly indexing, which could be causing the NA values.

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

Why not simply:

gsub('BSM', '"BSM"', 'Blamo BSM258 Clem on/o')

Upvotes: 1

Related Questions