Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (50.2k points)

In Rstudio, how can I obtain all the words that have two of a particular letter in them using the below-mentioned function:

  1. grep/grepl 
  2. sub/gsub

1 Answer

0 votes
by (108k points)

See if you want to get the states with two or more "a"s in them, then in that case use :

grep('.*a.*a.*',, value = TRUE, = TRUE)

The output in R programming will be:

# [1] "Alabama"        "Alaska"         "Arizona"        "Arkansas"      

# [5] "California"     "Delaware"       "Hawaii"         "Indiana"       

# [9] "Kansas"         "Louisiana"      "Maryland"       "Massachusetts" 

#[13] "Montana"        "Nebraska"       "Nevada"         "North Carolina"

#[17] "North Dakota"   "Oklahoma"       "Pennsylvania"   "South Carolina"

#[21] "South Dakota"  

And let say, you want exactly two "a"s, what you can do is use the str_count to count the number of "a"s and then perform the subsetting.[stringr::str_count(, 'a|A') == 2]

# [1] "Arizona"        "California"     "Delaware"       "Hawaii"        

# [5] "Indiana"        "Kansas"         "Louisiana"      "Maryland"      

# [9] "Massachusetts"  "Montana"        "Nebraska"       "Nevada"        

#[13] "North Carolina" "North Dakota"   "Oklahoma"       "Pennsylvania"  

#[17] "South Carolina" "South Dakota"

Browse Categories