【问题标题】:Duplicate elements in a list to have the same length as number of elements in a second list列表中的重复元素具有与第二个列表中的元素数量相同的长度
【发布时间】:2019-07-30 09:09:07
【问题描述】:

我正在使用 rvest 来抓取一些博客文章的 cmets 以及这些 cmets 所属的文章/博客文章的所属标题。 抓取本身效果很好,但现在我想将博客文章的标题和 cmets 分配给一个数据框。 当然,大部分博文都有多个 cmets,所以应该是这样的:

title_of_articleA     comment1
title_of_articleA     comment2
title_of_articleA     comment3
title_of_articleA     comment4
title_of_articleB     comment1
title_of_articleB     comment2

基本上这样我以后可以很容易地看到哪些 cmets 属于哪个帖子。

然而,我的问题是我目前有两个长度不同的列表(一个用于标题,另一个用于 cmets)。 在我可以使用 unlist() 并将它们组合之前,我需要以某种方式复制每个子列表 A 的元素,以匹配 B 的相关子列表中的项目数。

listA<-list("title_of_article 1", "title of article 2")
listB<-list(c("comment 1" ,"comment 2", "comment 3", "comment 4"), c("comment 1", "comment2"))

我可以使用 sapply(listB, length) 来接收我需要多少元素的指示符,但是我如何使用该信息告诉 ListA 相应地复制它的项目?

【问题讨论】:

    标签: r list


    【解决方案1】:

    这是一个使用tidyverse的选项

    library(tidyverse)
    set_names(listB, listA) %>% 
          enframe %>% 
          unnest
    # A tibble: 6 x 2
    #  name               value    
    #  <chr>              <chr>    
    #1 title_of_article 1 comment 1
    #2 title_of_article 1 comment 2
    #3 title_of_article 1 comment 3
    #4 title_of_article 1 comment 4
    #5 title of article 2 comment 1
    #6 title of article 2 comment 2
    

    【讨论】:

      【解决方案2】:

      listB的名称设置为unlist(listA),然后stack结果

      stack(setNames(listB, unlist(listA)))
      #     values                ind
      #1 comment 1 title_of_article 1
      #2 comment 2 title_of_article 1
      #3 comment 3 title_of_article 1
      #4 comment 4 title_of_article 1
      #5 comment 1 title of article 2
      #6 comment 2 title of article 2
      

      数据

      listA <- list("title_of_article 1", "title of article 2")
      listB <- list(c("comment 1" , "comment 2", "comment 3", "comment 4"), c("comment 1", "comment 2"))
      

      【讨论】:

        【解决方案3】:

        这是另一个使用mapply的想法,

        do.call(rbind, mapply(cbind, listA, listB))
        #     [,1]                 [,2]       
        #[1,] "title_of_article 1" "comment 1"
        #[2,] "title_of_article 1" "comment 2"
        #[3,] "title_of_article 1" "comment 3"
        #[4,] "title_of_article 1" "comment 4"
        #[5,] "title of article 2" "comment 1"
        #[6,] "title of article 2" "comment 2"
        

        【讨论】:

          猜你喜欢
          • 2021-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多