Reputation: 10996
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:
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
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