【问题标题】:Parent Child Identification based on character string in RR中基于字符串的父子标识
【发布时间】:2019-03-10 13:34:09
【问题描述】:

我有一个如下数据集,称为关键字:

输出如下:

逻辑是这样的:

  1. foldercount 列只不过是 Link 列中的“/”数
  2. Status 列只有 3 个值,Parent、Child 和 Orphan。
  3. 如果“链接”列中没有“/s”,则这些关键字的状态将为 - 孤立。
  4. 对于特定关键字,如果“/s”出现在链接中,并且该特定关键字的文件夹计数最少,则将其称为父级。存在“/s”的任何其他链接都是子链接。父母和孩子应该附加一个数字,这应该有助于我识别特定父母的孩子,例如 child1 是 parent1 的孩子。它可能发生在特定的关键字上,我们根本没有孩子。

我使用了以下代码,但它不符合我的目的:

Keyword$foldercount <- str_count(Keyword$URL, "/")
Keyword$last_char <- str_sub(Keyword$URL, -3,-1)
Keyword$last_char2 <- str_sub(Keyword$URL, -2,-1)

Keyword$isParent <- ifelse(Keyword$last_char == '/s/'| Keyword$last_char2 == '/s','Parent','Child')
Keyword$isParentDerivable <- "No"
h<- grep('/s/', Keyword$URL)
Keyword$isParentDerivable[h] <- "Y"

【问题讨论】:

  • 请分享dput(Keyword)作为样本数据

标签: r string


【解决方案1】:

您可以使用dplyr 轻松完成此类任务 由于您没有共享示例数据,因此我编了一些示例:

 Keyword <- data.frame(Keyword = c("shoes", "shoes", "laptop", "laptop", "orp"),
                    Link = c("www.abc.com/shoes/s/",
                                "www.abc.com/shoes/s/page=1/",
                                "www.abc.com/laptop/s/",
                                "www.abc.com/laptop/s/page2/",
                                "www.abc.com/cdcd"),
                       stringsAsFactors = F)

 library(dplyr)
 Keyword %>%
   mutate(foldercount = str_count(Link, "/")) %>%
   group_by(Keyword) %>%
   mutate(flag = ifelse(foldercount == min(foldercount), 1, 0)) %>%
   mutate(Status = ifelse(n() == 1, "Orphan", "Child")) %>%
   mutate(Status = ifelse(flag == 1 & n() > 1, "Parent", Status)) %>%
   mutate(Status = ifelse(Status != "Orphan", paste(Status, Keyword, sep = "_"), Status)) %>%
   select(-flag)
# A tibble: 5 x 4
# Groups:   Keyword [3]
  Keyword Link                        foldercount Status       
  <chr>   <chr>                             <int> <chr>        
1 shoes   www.abc.com/shoes/s/                  3 Parent_shoes 
2 shoes   www.abc.com/shoes/s/page=1/           4 Child_shoes  
3 laptop  www.abc.com/laptop/s/                 3 Parent_laptop
4 laptop  www.abc.com/laptop/s/page2/           4 Child_laptop 
5 orp     www.abc.com/cdcd                      1 Orphan

一旦你很好地理解了流水线,你就可以减少步骤的数量。

【讨论】:

  • 几个mutate 调用感觉有点“笨拙”,尽管在这种情况下它可能有助于提高可读性。可以使用一个mutate 呼叫。
  • 这解决了我的目的,但由于我的数据集很长,所以要花很长时间才能给出结果。有什么办法让它快点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
相关资源
最近更新 更多