简体   繁体   中英

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!

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM