R:切割字符串的等价物
R: Cut equivalent for strings
我有一份不同类型口罩的清单,我想将它们分为 N95、手术口罩、布口罩或其他口罩。
df<-data.frame(mask_type=
c("Surgical Mask (3M 1800)",
"N95 FFR (Wilson 1105N) (2x 3mm leaks)",
"N95 FFR (San Huei United Company 1895N) (2x 3mm leaks)",
"Surgical Mask (Primed PG4-1073) (2x 3mm leaks)",
"Surgical Mask (3M 1800) (2x 3mm leaks)",
"N95 FFR (Wilson 1105N) (4x 3mm leaks)",
"Cloth FFR (San Huei United Company 1895N) (4x 3mm leaks)",
"Cloth Mask (Primed PG4-1073) (4x 3mm leaks)")
这可以过滤掩码但不会创建“其他”列。你觉得我离你远吗?
要求(dplyr)
要求(tidyr)
df %>%
mutate(TYPE=stringr::str_detect(mask_type,"N95 | surgical | cloth")) %>%
filter(TYPE=TRUE) %>%
select(mask_type)
使用str_extract
提取字符串中是否存在任何模式'Surgical|N95|Cloth'
。如果 none 存在,它将 return NA
可以替换为 'Other'
.
library(dplyr)
library(stringr)
df %>%
mutate(TYPE= str_extract(mask_type, regex('Surgical|N95|Cloth', ignore_case = TRUE)),
TYPE = replace(TYPE, is.na(TYPE), 'Other'))
我们可以使用base R
lst1 <- with(df, regmatches(mask_type, gregexpr('Surgical|N95|Cloth', mask_type)))
df$TYPE <- sapply(lst1, function(x) if(length(x) == 0) 'Other' else x)
我有一份不同类型口罩的清单,我想将它们分为 N95、手术口罩、布口罩或其他口罩。
df<-data.frame(mask_type=
c("Surgical Mask (3M 1800)",
"N95 FFR (Wilson 1105N) (2x 3mm leaks)",
"N95 FFR (San Huei United Company 1895N) (2x 3mm leaks)",
"Surgical Mask (Primed PG4-1073) (2x 3mm leaks)",
"Surgical Mask (3M 1800) (2x 3mm leaks)",
"N95 FFR (Wilson 1105N) (4x 3mm leaks)",
"Cloth FFR (San Huei United Company 1895N) (4x 3mm leaks)",
"Cloth Mask (Primed PG4-1073) (4x 3mm leaks)")
这可以过滤掩码但不会创建“其他”列。你觉得我离你远吗?
要求(dplyr) 要求(tidyr)
df %>%
mutate(TYPE=stringr::str_detect(mask_type,"N95 | surgical | cloth")) %>%
filter(TYPE=TRUE) %>%
select(mask_type)
使用str_extract
提取字符串中是否存在任何模式'Surgical|N95|Cloth'
。如果 none 存在,它将 return NA
可以替换为 'Other'
.
library(dplyr)
library(stringr)
df %>%
mutate(TYPE= str_extract(mask_type, regex('Surgical|N95|Cloth', ignore_case = TRUE)),
TYPE = replace(TYPE, is.na(TYPE), 'Other'))
我们可以使用base R
lst1 <- with(df, regmatches(mask_type, gregexpr('Surgical|N95|Cloth', mask_type)))
df$TYPE <- sapply(lst1, function(x) if(length(x) == 0) 'Other' else x)