[英]R function that detects if a dataframe column contains string values from another dataframe column and adds a column that contains the detected str
我有兩個數據框:
df1:
姓名 |
---|
蘋果頁面 |
芒果頁面 |
荔枝汁 |
蔓越莓俱樂部 |
df2:
水果 |
---|
蘋果 |
葡萄 |
草莓 |
芒果 |
荔枝 |
蔓越莓 |
如果 df1$name 包含 df2$fruit 中的值(不區分大小寫),我想向 df1 添加一個列,該列具有 df1$name 包含的 df2$fruit 值。 df1 然后看起來像這樣:
姓名 | 類別 |
---|---|
蘋果頁面 | 蘋果 |
芒果頁面 | 芒果 |
荔枝汁 | 荔枝 |
蔓越莓俱樂部 | 蔓越莓 |
這應該有效:
library(stringr)
df1$category = str_extract(
df1$name,
pattern = regex(paste(df2$fruit, collapse = "|"), ignore_case = TRUE)
)
df1
# name category
# 1 Apple page Apple
# 2 Mango page Mango
# 3 Lychee juice Lychee
# 4 Cranberry club Cranberry
使用這些數據:
df1 = read.table(text = 'name
Apple page
Mango page
Lychee juice
Cranberry club', header = T, sep = ";")
df2 = read.table(text = 'fruit
Apple
Grapes
Strawberry
Mango
lychee
cranberry', header = T, sep = ";")
首先,您可以使用名稱作為占位符(僅填充 NA)為數據框的每個可能類別創建一列。 然后對於這些列中的每一個,檢查列名(即類別)是否出現在名稱中。 把它變成一個長數據框,然后刪除FALSE
行——那些沒有檢測到名稱中的類別的行。
library(tidyverse)
df1 <- tribble(
~name,
"Apple page",
"Mango page",
"Lychee juice",
"Cranberry club"
)
df2 <- tribble(
~fruit,
"Apple",
"Grapes",
"Strawberry",
"Mango",
"lychee",
"cranberry"
)
fruits <- df2$fruit %>%
str_to_lower() %>%
set_names(rep(NA_character_, length(.)), .)
df1 %>%
add_column(!!!fruits) %>%
mutate(across(-name, ~str_detect(str_to_lower(name), cur_column()))) %>%
pivot_longer(-name, names_to = "category") %>%
filter(value) %>%
select(-value)
#> # A tibble: 4 × 2
#> name category
#> <chr> <chr>
#> 1 Apple page apple
#> 2 Mango page mango
#> 3 Lychee juice lychee
#> 4 Cranberry club cranberry
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.