【问题标题】:sapply over vector for each element in a listsapply 对列表中的每个元素的向量
【发布时间】:2022-01-14 14:29:21
【问题描述】:

我有一个很大的列表,其中包括从语料库中提取的术语。

    mylist <- list(c("flower"), 
               c("plant", "animal", "cats", "doggy"),
               c("tree", "trees", "cat", "dog"))

提取的术语来自数据框(作为主要词、相似词和类别)

   ref <- data.frame(id = c(1:5), 
                  main = c("tree", "plant", "flower", "dog", "cat"), 
                  similar = c("trees","plantlike", "flowery", "doggy", "cats"),
                  category = c("plant", "plant", "plant", "animal", "animal"))

我需要更改列表,以便使用类别而不是单词。并且可能会删除这样的重复项...

    needed <- list("plant",
                   c("plant", "animal", "animal", "animal"),
                   c("plant", "plant", "animal", "animal"))
    
    orbetter <- list("plant",
                   c("plant", "animal"),
                   c("plant", "animal"))

但我不知道如何为列表中的每个元素应用 sapply。感谢您的帮助。

【问题讨论】:

  • 如何从myListneeded?您是否正在针对 ref 执行查找?
  • @emilliman5 是的 .. 我想将单词与参考数据框匹配。

标签: r list lapply sapply


【解决方案1】:
mylist <- list(c("flower"), 
               c("plant", "animal", "cats", "doggy"),
               c("tree", "trees", "cat", "dog"))

ref <- data.frame(id = c(1:5), 
                  main = c("tree", "plant", "flower", "dog", "cat"), 
                  similar = c("trees","plantlike", "flowery", "doggy", "cats"),
                  category = c("plant", "plant", "plant", "animal", "animal"))

library(tidyr)

ref_long <- ref %>% 
  pivot_longer(-c(id, category))

lapply(mylist, function(x) unique(ref_long$category[match(x, table = ref_long$value)]))
#> [[1]]
#> [1] "plant"
#> 
#> [[2]]
#> [1] "plant"  NA       "animal"
#> 
#> [[3]]
#> [1] "plant"  "animal"

reprex package (v2.0.1) 于 2022-01-14 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2021-10-04
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多