3

我正在尝试获取一个profiles包含一列email地址的数据框,并添加一个由每个电子邮件地址的可注册域部分组成的新列,domain.

registerable_domains在一个过于复杂的过程中单独创建唯一的向量,无法针对数据帧中的每一行运行,其结果是一个向量,该向量必然小于profiles数据帧中的行数。然后我检查向量中的每个条目是否出现在数据帧中每个地址registerable_domains的末尾,并将数据帧的列条目设置为匹配的位置。emailprofilesdomain

下面的代码是可复制的数据,您可以复制粘贴并在 R 中执行,每行注释以解释它的作用。

for()循环正是我想做的:它在数据框的domain列中创建适当的条目。profiles问题是在这个例子中,profiles数据框有 12 行,registerable_domains向量有 8 个条目。在实际数据集中,profiles数据框有大约 500,000 行,registerable_domains向量有大约 110,000 个条目。结果,虽然for()循环适用于小数据集,但对于非常大的数据集,我需要一种不同的方法(我的估计是,这种方法需要大约 75 年才能在完整的数据集上完成!)。

非常感谢您帮助将此for()循环转换为大型数据集的时间实际操作。我查看了许多其他线程,但找不到任何解决这种特殊情况的答案(尽管解决了许多其他类似但不同的情况)。谢谢!

# Data frame consisting of a column of 12 emails, and a column of 12 NA entries:

email <- c( "john@doe.com",
            "mary@smith.co.uk",
            "peter@microsoft.com",
            "jane@admins.microsoft.com",
            "luke@star.wars.com",
            "leia@star.wars.com",
            "yoda@masters.star.wars.com",
            "grandma@bletchly.ww2.wars.com",
            "searchfor@janedoe.com",
            "fan@mail.starwars.com",
            "city@toronto.ca",
            "area@toronto.canada.ca");

domain <- c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA);

profiles <- data.frame(email, domain);

profiles; # See what the initial data frame looks like

#                            email domain
# 1                   john@doe.com     NA
# 2               mary@smith.co.uk     NA
# 3            peter@microsoft.com     NA
# 4      jane@admins.microsoft.com     NA
# 5             luke@star.wars.com     NA
# 6             leia@star.wars.com     NA
# 7     yoda@masters.star.wars.com     NA
# 8  grandma@bletchly.ww2.wars.com     NA
# 9          searchfor@janedoe.com     NA
# 10         fan@mail.starwars.com     NA
# 11               city@toronto.ca     NA
# 12        area@toronto.canada.ca     NA

# Vector consisting of email addresses stripped to registerable domain component only, created through a separate process that is too complex to run on each row entry:

registerable_domains <- c(  "doe.com",
                            "smith.co.uk",
                            "microsoft.com",
                            "wars.com",
                            "janedoe.com",
                            "starwars.com",
                            "toronto.ca",
                            "canada.ca");

# Credit to Nick Kennedy for his help with this original solution (http://stackoverflow.com/users/4998761/nick-kennedy)

for (domains in registerable_domains) {                                             # Iterate through each of the registerable domains
    domains_pattern <- paste("[.@]", domains, "$", sep="");                         # Add regex characters to ensure that it's only the end part to deal with nested domain names
    found <- grepl(domains_pattern, profiles$email, ignore.case=TRUE, perl=TRUE);   # Grep for the current domain pattern in all of the emails and build a boolean table for entry locations
    profiles[which(found & is.na(profiles$domain)), "domain"] <- domains;           # Modify profile data table at TRUE entry locations not yet set
}

profiles; # Expected and desired outcome:

#                            email        domain
# 1                   john@doe.com       doe.com
# 2               mary@smith.co.uk   smith.co.uk
# 3            peter@microsoft.com microsoft.com
# 4      jane@admins.microsoft.com microsoft.com
# 5             luke@star.wars.com      wars.com
# 6             leia@star.wars.com      wars.com
# 7     yoda@masters.star.wars.com      wars.com
# 8  grandma@bletchly.ww2.wars.com      wars.com
# 9          searchfor@janedoe.com   janedoe.com
# 10         fan@mail.starwars.com  starwars.com
# 11               city@toronto.ca    toronto.ca
# 12        area@toronto.canada.ca     canada.ca
4

3 回答 3

3

这是使用的解决方案dplyr

library(dplyr)
person <- data_frame(Email = email) %>% 
  mutate(Domain = gsub("^.*@", "", Email)) # everything upto the last @
domain <- person %>% 
  select(Domain) %>% # select the Domain variable
  distinct() %>%  # keep only unique rows
  mutate(Original = Domain) # copy Domain into Original
extra <- domain %>% 
  mutate(Domain = gsub("^[[:alnum:]]*\\.", "", Domain)) %>% # remove all alphanumeric characters upto the first point and overwrite Domain
  filter(grepl("\\.", Domain)) # keep only observations where domain contains at least one point
while (nrow(extra) > 0){
  domain <- bind_rows(domain, extra) #add the rows from extra to domain
  extra <- extra %>% 
    mutate(Domain = gsub("^[[:alnum:]]*\\.", "", Domain)) %>% 
    filter(grepl("\\.", Domain))
}
register <- data_frame(Domain = registerable_domains)
register %>% 
  inner_join(domain, by = "Domain") %>% #join the two table on a common Domain
  inner_join(person, by = c("Original" = "Domain")) # join the resulting table to person where result.Original = person.Domain
于 2015-10-12T22:22:30.957 回答
1

我认为你可以通过追求简单的果实并将一些for易于矢量化的操作从你的循环中取出来显着减少你的时间。

profiles <- profiles %>% mutate(test_domains = sub(".*@", "", email))

很容易,并且只是为您提供了一个新列来使用,而不是在每次迭代中花费时间。

for (d in registerable_domains){
    profiles$domain[d == profiles$test_domains] <- d
}

将采用直接匹配,并且应该只为那些仍然具有的行留下当前昂贵的循环NA,即

profiles[is.na(profiles$domain)]

这将是一个适当的子集。我不知道它可以为您节省多少,我现在必须离开。我将回到这一点。感谢您写的关于数据的好问题。

于 2015-10-12T22:51:56.580 回答
0

不确定这是否有帮助,因为我完全改变了 for 循环的理念及其作用。另外,我没有意识到您是否真的需要可注册的域。但是,我的想法不是拥有一个可注册域列表,而是使用这些域所具有的模式,并将它们应用到您的电子邮件列表中。

例如,如果域以 结尾com,或者ca你保留这部分和左边的内容,比如searchfor@janedoe.com变成janedoe.com。如果域以 结尾uk,那么您需要这部分,您还需要co以及之前的内容。

如果您设法发现这些模式,您可以使用 if-else 规则创建一个简单的函数并执行类似的操作

x = c("luke@star.wars.com",
     "area@toronto.canada.ca",
     "mary@smith.co.uk")

dt = data.frame(x, stringsAsFactors = F)

dt

#                        x
# 1     luke@star.wars.com
# 2 area@toronto.canada.ca
# 3       mary@smith.co.uk

ff = function(x){
  x = strsplit(x, split = "[[:punct:]]")[[1]]

  ifelse(x[length(x)] %in% c("com","ca"),
         paste(x[(length(x)-1):length(x)], collapse = "."),
         paste(x[(length(x)-2):length(x)], collapse = "."))}

dt$v = sapply(dt$x, ff)

dt

#                        x           v
# 1     luke@star.wars.com    wars.com
# 2 area@toronto.canada.ca   canada.ca
# 3       mary@smith.co.uk smith.co.uk
于 2015-10-12T22:33:09.590 回答