Thirst for Knowledge Thirst for Knowledge - 2 months ago 10
R Question

R - splitting a string two characters before the end

This is a similar question to this previous query.

However, this time I want to split the postcodes up two characters before the end of the string. How do I do this please?

For example, I have postcode data in R that looks like this, having had the central space removed:

Postcodes
AB46JK
AR148UI
D49IK
CB39EU


But I want to split the postcodes into postcode sectors, which now includes everything two characters before the end of the string, so that they look like this:

Postcodes
AB46
AR148
D49
CB39


Help would be much appreciated.

Answer

Base R, non-regex solution:

substring(postcodes, 1, nchar(postcodes)-2 )