sub a pattern in a data frame in r except for when it includes another pattern

Viewed 52

I have a df with rows in a specific column containing the following

temp1_01_100, temp2_01_100, temp2_02_100, s10_100, s11_100, s12_100, s21_100

enter image description here

I would like to replace the "_100" with "" e.g. doing that df$col <- sub("_100.*", "", df$col) but I don't want the replacement when there is the pattern "temp" no matter if it's temp1 or temp2.

the output I want is:

temp1_01_100, temp2_01_100, temp2_02_100, s10, s11, s12, s21

2 Answers

Input

> vec
[1] "temp1_01_100" "temp2_01_100" "temp2_02_100" "s10_100"      "s11_100"      "s12_100"      "s21_100"

Code

vec[!grepl("temp", vec)] <- gsub("_100", "", vec[!grepl("temp", vec)])

Output

> vec
[1] "temp1_01_100" "temp2_01_100" "temp2_02_100" "s10"          "s11"          "s12"          "s21"  

Addendum

For your situation, try directly with

df$col[!grepl("temp", df$col)] <- gsub("_100", "", df$col[!grepl("temp", df$col)])

You can try gsub like below

> gsub("(?<=s\\d{2})_100", "", vec, perl = TRUE)
[1] "temp1_01_100" "temp2_01_100" "temp2_02_100" "s10"          "s11"
[6] "s12"          "s21"

Data

vec <- c("temp1_01_100", "temp2_01_100", "temp2_02_100", "s10_100", "s11_100", "s12_100", "s21_100")
Related