1
votes

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?

1
substr(code, 1, 3) or sub("^(.{3}).*", "\\1", code)akrun
Much simpler than the gsub method, thanks Akrun!Tox

1 Answers

4
votes

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)