deschen
deschen

Reputation: 10996

R replace part of a string conditionally by a vector of possible replacements

Assume a data frame in R, where I have (among others) the following column:

V1
Q1r2c5
Q1r5c11
Q1r5_1c130

I have a second data frame, which looks like:

search    replace
5         brand1
11        brand2
130       brand3

What I want to do is the following: in Data frame one search for the part behind the "c" in V1 and replace it with the matched replacement from the second dataframe. Thus:

  1. Q1r2c5 becomes to "brand1"
  2. Q1r5c11 becomes "brand2"
  3. Q1r5_1c130 becomes "brand3"

I have tried out gsub(".*c", "", dataframe$V1") which indeed gives me the part behind the "c". However, I have not yet found a simple way (except via for loops) to do the matching based on the second data frame.

Any ideas? Thanks a lot!

Upvotes: 0

Views: 255

Answers (1)

zyurnaidi
zyurnaidi

Reputation: 2273

You can use match to produce the replacement. In below example I add one more data to the first data frame, to check things out.

V1 <- read.table(text="Q1r2c5
                 Q1r5c11
                 Q1r5_1c130
                 testc130", stringsAsFactors=F)
V2 <- read.table(text = "search    replace
                 5         brand1
                 11        brand2
                 130       brand3", header = T, stringsAsFactors=F)

V2$replace[match(sub(".*c", "", V1$V1), V2$search)]
[1] "brand1" "brand2" "brand3" "brand3"

Upvotes: 1

Related Questions