Extract first word from a column and insert into new column

Nick picture Nick · Aug 10, 2015 · Viewed 30.2k times · Source

I have a dataframe below and want to extract the first word and insert it into a new column

Dataframe1:

COL1
Nick K Jones
Dave G Barros
Matt H Smith

Convert it to this:

Dataframe2:
COL1              COL2
Nick K Jones      Nick
Dave G Barros     Dave
Matt H Smith      Matt

Answer

Rorschach picture Rorschach · Aug 10, 2015

You can use a regex ("([A-Za-z]+)" or "([[:alpha:]]+)"or "(\\w+)") to grab the first word

Dataframe1$COL2 <- gsub("([A-Za-z]+).*", "\\1", Dataframe1$COL1)