【问题标题】:How to get rows with elements in the list column如何获取列表列中包含元素的行
【发布时间】:2019-10-10 07:31:31
【问题描述】:

我有一个如下的数据表:

library(data.table)

dt <- data.table(
  id = c(1:3),
  string = list(c("tree", "house", "star"),  
                c("house", "tree", "dense forest"), 
                c("apple", "orange", "grapes"))
  )

由此我想获取列表字符串列中包含“tree”的行。 所以我尝试了

dt["tree" %in% string]
Empty data.table (0 rows) of 2 cols: id,string


dt["tree" %in% unlist(string)]
   id                  string
1:  1         tree,house,star
2:  2 house,tree,dense forest
3:  3     apple,orange,grapes

我不确定我做错了哪一部分。我只需要返回 id 1 和 2。感谢任何帮助。

【问题讨论】:

    标签: r data.table stringi


    【解决方案1】:

    或者只是

    library(data.table)
    dt[grep("\\btree\\b", string)]
    
       id                  string
    1:  1         tree,house,star
    2:  2 house,tree,dense forest
    

    看起来你的方法有什么问题是%in% 不适用于列表

    "tree" %in% dt$string[1]
    [1] FALSE
    

    而 grep() 或 grepl() 接受它可以强制转换为字符向量的所有内容

    grepl("tree", dt$string[1])
    [1] TRUE
    
    as.character(dt$string[1])
    [1] "c(\"tree\", \"house\", \"star\")"
    

    这意味着它还将匹配其他单词与tree 在 IF 作为@RonakShah 提醒我你不要使用单词边界\b。

    【讨论】:

    • 这也将选择带有单词"treed"或"atree"的行,任何带有“tree”的单词。
    【解决方案2】:

    由于string 是一个列表,您需要sapply 或其他方式来遍历每个列表。

    library(data.table)
    dt[sapply(string, function(x) any(x == "tree"))]
    
    #   id                  string
    #1:  1         tree,house,star
    #2:  2 house,tree,dense forest
    

    【讨论】:

      【解决方案3】:

      我们也可以使用stringr中的str_detect

      library(dplyr)
      library(stringr)
      dt %>%
         filter(str_detect(string, "\\btree\\b"))
      #   id                    string
      #1  1         tree, house, star
      #2  2 house, tree, dense forest
      

      或者在data.table中使用Map

      dt[unlist(Map(`%in%`, "tree", string))]
      #   id                  string
      #1:  1         tree,house,star
      #2:  2 house,tree,dense forest
      

      【讨论】:

        猜你喜欢
        • 2011-12-29
        • 1970-01-01
        • 1970-01-01
        • 2022-12-01
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 2021-02-22
        • 2013-09-17
        相关资源
        最近更新 更多