Extract first word from a column and insert into new column [duplicate]

一曲冷凌霜 提交于 2019-11-27 22:10:59

问题


This question already has an answer here:

  • Remove everything after space in string 4 answers

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

回答1:


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)



回答2:


We can use function stringr::word:

library(stringr)

Dataframe1$COL2 <- word(Dataframe2$COL1, 1)



回答3:


The function strsplit can be useful

Dataframe1$COL2 <- strsplit(Dataframe1$COL1, " ")[[1]][1]

Then you can change the last bracketed number to select other parts from the string too.



来源:https://stackoverflow.com/questions/31925811/extract-first-word-from-a-column-and-insert-into-new-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!