【问题标题】:generate user variable from email variable with dplyr?使用 dplyr 从电子邮件变量生成用户变量?
【发布时间】:2016-01-26 19:32:43
【问题描述】:

我有一个如下所示的数据框:

df1 <-
  structure(
    list(email = c(
      "user1@email.com", "user2@othermail.org"
    )), class = "data.frame", .Names = "email", row.names = c(NA,-2L)
  )

我想生成一个新变量user。我试过这个:

df2 <- df1 %>% mutate(user=strsplit(email, split = '@'))

但我希望 user 只是用户的字符变量,而不是带有 to 元素的列表。我该怎么做?

【问题讨论】:

    标签: r dplyr strsplit


    【解决方案1】:

    您也可以使用基本 R 并删除您不想要的字符。

    df1 <-
      structure(
        list(email = c(
          "user1@email.com", "user2@othermail.org"
        )), class = "data.frame", .Names = "email", row.names = c(NA,-2L)
      )
    
    df2 <- df1
    df2$user <- gsub("@.*", "", df1$email)
    df2
    #                 email  user
    # 1     user1@email.com user1
    # 2 user2@othermail.org user2
    

    【讨论】:

      【解决方案2】:

      我们可以从tidyr使用separate

      library(dplyr)
      library(tidyr)
      separate(df1, email, into=c('user', 'com'), 
                         sep="@", remove=FALSE) %>% 
             select(-com)
      #                 email  user
      # 1     user1@email.com user1
      # 2 user2@othermail.org user2
      

      或者正如@docendo discimus 所提到的,extract 也可以通过将要提取的字符指定为捕获组中的新列 ((.*)) 来使用,然后是所有其他要删除的字符(即 @ 和多个字符之一 (.*))

      extract(df1, email, "user", "(.*)@.*", remove = FALSE) 
      

      使用 OP 的代码,strsplit 输出将是 list。如果需要从每个list 元素中提取第一个元素,请使用lapply

       df1 %>%
          mutate(user=lapply(strsplit(email, split = '@'),"[[", 1))
      

      【讨论】:

      • extract(df1, email, "user", "(.*)@.*", remove = FALSE)
      【解决方案3】:

      我们可以通过选择从strsplit返回的每个列表的第一个元素来对您的原始代码进行小修改:

      df2 <- df1 %>% mutate(user=lapply(strsplit(email, split = '@'), "[", 1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多