【问题标题】:Extract Email and Put it in Adjacent Row提取电子邮件并将其放入相邻行
【发布时间】:2018-04-23 11:03:15
【问题描述】:

我有数据集。

v1 <- c("I will try to fix you usman@usman.com", "I will try to fix you", "Zombies Zombies xyz@ymail.com")
v2 < c("ABC", "XYZ", "Oh Game")
dx <- data.frame(v1, v2)

我使用

v1 提取电子邮件

regmatches(dx$v1, regexpr("[[:alnum:]]+\\@[[:alpha:]]+\\.com", dx$v1))

这行得通。

我只想将电子邮件与v2 相邻放在dx

这样。

ABC       usman@usman.com
XYZ       NA
Oh Game   xyz@ymail.com

看起来很基本,但我无法弄清楚。

【问题讨论】:

    标签: r regex dplyr


    【解决方案1】:

    一种方法可能是

    dx$emails <- sapply(dx$v1, function(x) {
      email <- regmatches(x, regexpr("[[:alnum:]]+@[[:alpha:]]+\\.com", x))
      (result <- ifelse(identical(email, character(0)), NA, email))
    })
    

    这基本上检查是否找到至少一个匹配项。


    如果您不介意安装软件包,请使用 stringr 并在表达式周围加上括号(@ 不需要转义):
    library(stringr)
    dx$emails <- str_extract(dx$v1, "([[:alnum:]]+@[[:alpha:]]+\\.com)")
    


    两者都会产生
                                         v1      v2          emails
    1 I will try to fix you usman@usman.com     ABC usman@usman.com
    2                 I will try to fix you     XYZ            <NA>
    3         Zombies Zombies xyz@ymail.com Oh Game   xyz@ymail.com
    

    【讨论】:

    • 嘿@Jan,谢谢,这似乎运作良好,感谢您提供basestringr 解决方案。
    猜你喜欢
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多