Tox Tox - 29 days ago 12
R Question

Display first 3 characters using gsub in R

I have a column with codes of 4 characters and I would like to make a second column which only gives the first 3 characters of the first columns.

So if the first code is 1234 I would like to have 123 in the second column.

I am currently looking into gsub and with the following code I can display the first character.

code<-1234
gsub("(?<!^)(..)", "", code, perl=TRUE)


Does anyone know how I could extract the first three characters?

Answer Source

We can either use substr

substr(code, 1, 3)

or with sub to capture the three characters ((.{3})) from the start (^) of the string as a group followed by other character and replace with the backreference (\\1) of the capture group

sub("^(.{3}).*", "\\1", code)