如何从 R 中的各种字符串模式中过滤行

问题描述 投票:0回答:1

我有一个很大的数据框,其中有一列包含数字和字母代码。像这样的东西:

身份证 死亡原因
1 K703
2 N19X
3 C069
4 C07X
5 D181
6 R99X
7 D371
8 E117
9 D489
10 D500

我需要过滤并保留所有以字母C开头的代码和以字母D开头的代码,但仅限于0到48之间的数字(即D00,D10,D20,D48),D49开始的数据不再是需要。

我已经成功过滤掉了字母 C 代码,因为很容易要求使用 dplyr 和 stringr 保留以字母 C 开头的字符。

df_filtered <- df %>% 
  filter(str_detect(death_cause, "^C"))

但是,我还需要保留特定的 D 代码。 我的一个想法是用 D 代码的字符创建一个向量

D_codes <- paste("D", 00:48, sep = "")

我的问题是如何使用 dplyr 和 stringr(一般来说是 tidyverse)函数过滤 C 代码旁边的其他字符模式。

我尝试过:

 df_filtered <- df %>% 
      filter(str_detect(death_cause, "^C") | str_detect(death_cause, D_codes ) )

如果您能给我任何帮助,我将不胜感激。

r dplyr tidyverse stringr
1个回答
0
投票

您走在正确的道路上。您需要为您的 D 代码填充个位数:

library(stringr)

D_codes <- str_c("D", str_pad(0:48, 2, pad = "0"))

并且只需使用

%in%
而不是
str_detect()
:

df %>% 
  filter(str_starts(death_cause, "C") | death_cause %in% D_codes))
© www.soinside.com 2019 - 2024. All rights reserved.