Tox
Tox

Reputation: 854

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?

Upvotes: 1

Views: 2850

Answers (1)

akrun
akrun

Reputation: 887621

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)

Upvotes: 4

Related Questions