0

I have a table which has a column of emails. I'd like to split it into two columns, one for the username and the other for the domain. I have tried a couple solutions, but I'm having trouble manipulating the lists.

I can use str_locate() to find the location for the @ and use that to split. I can also use str_split.

Here is the code that I used.

my_df %>% mutate(domain = str_locate(du_email, "@")[1])

The problem is that str_locate returns a list. When I do not include a slice, [1], then I get an error because it creates too many values and when I do include a slice, then all of the values get filled with the output of the first result.

Cauder
  • 2,157
  • 4
  • 30
  • 69

1 Answers1

2

You can use

library(dplyr)

df <- data.frame(ID = c(1,2,3,4,5),
             Email = c("1@gmail.com","2@hotmail.com","3@test.com","4@yahoo.com","5@gmail.com"))

test <- df%>%
  mutate(user = gsub("@.*","",Email))%>%
  mutate(Domain = gsub(".*@","",Email))%>%
  select(-Email)

   ID user      Domain
1  1    1   gmail.com
2  2    2 hotmail.com
3  3    3    test.com
4  4    4   yahoo.com
5  5    5   gmail.com
Aaron Parrilla
  • 522
  • 3
  • 13