Question: I would like to insert a string `"_2010_"` after the `.` in the `colnames` of a `data.frame`

```
data("iris")

> names(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"  

```

Desired **output**:

```
[1] "Sepal._2010_Length" "Sepal._2010_Width"  "Petal._2010_Length" "Petal._2010_Width"  "Species"  

```

help ?

**EDIT:**
related question: now how to insert the string `"_2010_"` **before** the `.` ?

```
[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length" "Petal_2010_.Width"  "Species"  

```

Answer: 
We can use `sub` and on the `names` of 'iris' which has a `.` (by subsetting with `grep`). Here, we use capture groups (`(...)`) and replace with the backreferences (`\\1`) along with the newly added substrings (`_2010_`).

```
i1 <- grep("[.]", names(iris))
name(iris)[i1] <- sub("([^.]+.)(.*)", "\\1_2010_\\2", names(iris)[i1])

```

---

Or using a single capture group where we match a dot (`.\\`) followed by characters until the end of the string in a capture group. Replace it with a dot followed by the substring and the backreference.

```
sub("\\.(.*)", "._2010_\\1", names(iris))
#[1] "Sepal._2010_Length" "Sepal._2010_Width"  "Petal._2010_Length"
#[4] "Petal._2010_Width"  "Species"      

```

If we need the string before the `.` just change the order of placement of strings in the replacement

```
sub("\\.(.*)", "_2010_.\\1", names(iris))
#[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length"
#[4] "Petal_2010_.Width"  "Species"  

```
The function `str_replace` in the package `stringr` is ideal for this problem, and very easy to use.

```
library(stringr)
str_replace(names(iris), "\\.", "_2010_.")
#[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length" 
#[4] "Petal_2010_.Width"  "Species"

```

If you want `.` before the first `_`, just put `"._2010_"` in your syntax for `str_replace`. We use `\\.` and not just `.` because the dot already has meaning and we need to escape that if we want to match it specifically (<http://regexone.com/lesson/wildcards_dot>).