使用dplyr从电子邮件变量生成用户变量?

时间:2016-01-26 19:32:43

标签: r dplyr strsplit

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

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 = '@'))

但我希望用户只是一个用户的字符变量,而不是带有元素的列表。我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

你也可以使用基数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

答案 1 :(得分:2)

我们可以使用separate

中的tidyr
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提到的那样,extract也可以通过指定要提取的字符作为捕获组((.*))中的新列,然后删除所有其他列(即@ .*和一个或多个字符(extract(df1, email, "user", "(.*)@.*", remove = FALSE) ))

strsplit

使用OP的代码,list输出将是list。如果需要从每个lapply元素中提取第一个元素,请使用 df1 %>% mutate(user=lapply(strsplit(email, split = '@'),"[[", 1))

.panel .title, c {
    ...
    writing-mode: vertical-rl;
    ...
}

答案 2 :(得分:1)

我们只需选择从strsplit返回的每个列表的第一个元素,即可对原始代码进行少量修改:

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