BCArg BCArg - 3 months ago 9
R Question

R - insert a character in multiple strings in a list

below I am displaying the head of a data frame composed of 358 rows and a single column.

|V1 |
|:-----------|
|LmjF36.6910 |
|LmjF36.6650 |
|LmjF36.5620 |
|LmjF36.5150 |
|LmjF36.5010 |
|LmjF36.3910 |


For all the 358 rows I would like to insert a "." (dot) after the fourth character, so that I would like my table to look like the one displayed below:

|V1 |
|:------------|
|LmjF.36.6910 |
|LmjF.36.6650 |
|LmjF.36.5620 |
|LmjF.36.5150 |
|LmjF.36.5010 |
|LmjF.36.3910 |


Does anyone have an idea of how to do it for all my 358 rows?

Thanks in advance.

Answer
df$V1 <- sub('^(.{4})','\\1.',df$V1);
df;
##             V1
## 1 LmjF.36.6910
## 2 LmjF.36.6650
## 3 LmjF.36.5620
## 4 LmjF.36.5150
## 5 LmjF.36.5010
## 6 LmjF.36.3910

Data

df <- data.frame(V1=c('LmjF36.6910','LmjF36.6650','LmjF36.5620','LmjF36.5150','LmjF36.5010',
'LmjF36.3910'),stringsAsFactors=F);