简体   繁体   English

提取观察值包含 R 中某个字符的行

[英]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).例如,“Abbot Point”的端口有“Abbot Point Anch”作为下一个观察值(见附件截图)。

I want to extract all the rows that have "Anch" in them to a new variable called "Anchorages".我想将所有包含“Anch”的行提取到一个名为“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.我在“端口”变量中有 219 行,但并非所有端口都有锚点,因此例如,我不能每隔一行 select。 I am fairly new at R so not sure if this is even possible haha.我在 R 相当新,所以不确定这是否可能哈哈。

This is what I have tried but I'm not getting the output I want, it has only given me the characters before "Anch":这是我尝试过的,但我没有得到我想要的 output,它只给了我“Anch”之前的字符:

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

Screenshot of the first few rows of my variable "Ports"我的变量“Ports”前几行的屏幕截图

Any suggestions will be greatly appreciated!任何建议将不胜感激!

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)代表 package (v2.0.1) 于 2022 年 9 月 1 日创建

Do either of these solve your problem?这些中的任何一个都能解决您的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM