Adam Majdi Adam Majdi - 6 months ago 23
R Question

Insert a space at a specific location in a string

I have a data frame and want to insert a space at a specific location. Here is an example of the data:


And here is what I want to get (a space before any letter H):

0M HOCAN000006026421 HOCAN000000392457 HOCAN000005311227
0F HOUSA000002272874 HOUSA000002272874 HOUSA000050206641
0M HOUSA000002272874 HOUSA000002076121 HOUSA000014569699


We can use fixed width read:

read.fwf("temp.txt", widths = c(2, 17, 17, 17))
#   V1                V2                V3                V4
# 1 0M HOCAN000006026421 HOCAN000000392457 HOCAN000005311227
# 2 0F HOUSA000002272874 HOUSA000002272874 HOUSA000050206641
# 3 0M HOUSA000002272874 HOUSA000002076121 HOUSA000014569699

This solutions should work, even if IDs do not start with letter H and IDs can contain more than one H.