首页 > 解决方案 > Extracting words of a vector with names

问题描述

This is my vector:

m.v<- c("Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr", 
    "Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr")

How can I create another vector with only the first name before the ~?

So, how can I extract the first names?

标签: rregexstring

解决方案


Here you have some other alternatives:

> gsub("~.*$", "", m.v)
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"


> library(stringr)
> str_extract(m.v, "^\\w+")
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"

推荐阅读