我有一个包含电子邮件的数据集,例如:
my_df <- data.frame(email = c("mirko@asdoi.com", "elsa@asodida.co.uk", "elsapina@asoqw.com"))
我有一个开源数据集,例如:
open_data <- data.frame(name = c("mirko", "elsa", "pina"), gender = c("male", "female", "male")
结果应为:
result <- data.frame(email = c("mirko@asdoi.com", "elsa@asodida.co.uk", "elsapina@asoqw.com", "elsapina@asoqw.com"), gender = c("male", "female", "female", "male))
答案 0 :(得分:2)
一种选择是使用sqldf
库,并通过两个数据框之间的数据库样式连接来解决此问题:
library(sqldf)
my_df$name <- sub("@.*$", "", my_df$email)
sql <- "select t1.email, t2.gender from my_df t1 inner join open_data t2 "
sql <- paste0(sql, "on t1.name like '%' || t2.name || '%'")
result <- sqldf(sql)
答案 1 :(得分:0)
也许符合这些原则?不确定在更复杂的情况下这有多强。
library(tidyverse)
open_data %>%
rowwise() %>%
mutate(email = list(grep(name, my_df$email))) %>%
unnest() %>%
mutate(email = my_df$email[email])
## A tibble: 4 x 3
# name gender email
# <fct> <fct> <fct>
#1 mirko male mirko@asdoi.com
#2 elsa female elsa@asodida.co.uk
#3 elsa female elsapina@asoqw.com
#4 pina male elsapina@asoqw.com
说明:我们使用grep
在open_data$name
中找到my_df$email
的匹配项;然后unnest
展开多个匹配项,并使用行索引提取email
条目。