Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract rows where an observation contains a certain character in R

I have a variable "Ports" that has names of ports and some of these ports have an anchorage associated with them. For example the port of "Abbot Point" has "Abbot Point Anch" as the next observation (see attached screenshot).

I want to extract all the rows that have "Anch" in them to a new variable called "Anchorages". I have 219 rows in the "Ports" variable but not all ports have an anchorage so I can’t select every second row for example. I am fairly new at R so not sure if this is even possible haha.

This is what I have tried but I’m not getting the output I want, it has only given me the characters before "Anch":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Anchorages <- sub("Anch.*", "", Ports)
> head(Anchorages)
[1] "c(\"Abbot Point\", \"Abbot Point "

Screenshot of the first few rows of my variable "Ports"

Any suggestions will be greatly appreciated!

>Solution :

Here are two potential options:

ports <- data.frame(PORT_NAME = c("Abbot Point", "Abbot Point Anch",
                                  "Adelaide", "Adelaide Anch",
                                  "Airlie", "Albany"))

ports
#>          PORT_NAME
#> 1      Abbot Point
#> 2 Abbot Point Anch
#> 3         Adelaide
#> 4    Adelaide Anch
#> 5           Airlie
#> 6           Albany

# base R option
Anch_ports <- subset(ports, grepl("Anch", PORT_NAME))
Anch_ports
#>          PORT_NAME
#> 2 Abbot Point Anch
#> 4    Adelaide Anch

# tidyverse option
library(tidyverse)
Anch_ports <- ports %>%
  filter(str_detect(ports$PORT_NAME, "Anch"))
Anch_ports
#>          PORT_NAME
#> 1 Abbot Point Anch
#> 2    Adelaide Anch

Created on 2022-09-01 by the reprex package (v2.0.1)

Do either of these solve your problem?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading