mlosada
mlosada

Reputation: 75

How to retain words with a special character in r

I have a set of words like this one:

ctr_names <- c("Czech_Republic","New_Zealand","Great_Britain", "Spain", "France")

I want to RETAIN JUST words with "_" characters and remove the rest of words. I wish a final result as:

[1] "Czech_Republic" "New_Zealand"    "Great_Britain" 

I've been trying with

gsub("[_]", " ", ctr_names)

but it does not work because it remove the character I wanna retain. Any help will be appreciated

Upvotes: 2

Views: 56

Answers (2)

Phil
Phil

Reputation: 8117

Tidyverse way:

library(stringr)
str_subset(ctr_names, "_")

Upvotes: 1

neilfws
neilfws

Reputation: 33782

One way:

grep("_", ctr_names, value = TRUE)

grep functions match things. sub functions substitute things.

Upvotes: 1

Related Questions