【问题标题】:How to check whether a specific element exists in a list of dataframes in R?如何检查 R 中的数据框列表中是否存在特定元素?
【发布时间】:2021-03-05 06:05:10
【问题描述】:

假设我有以下数据框列表:

A = list(fruits = data.frame(V1 = c("Apple", "Banana", "Orange")), vegetables = data.frame(V1 = c("cucumber", "lettuce")))

我想知道生菜存在于列表的“蔬菜”数据框中,但不存在于水果中(可能是 TRUE 或 FALSE 或 0 或 1 输出)

我尝试了以下功能:

map_lgl(A, `%in%`, x = "lettuce") %>% as.integer()

但我得到的输出是 0 0。我还需要输出表明“蔬菜”是在其中找到“生菜”的列表中的数据框

似乎我需要以某种方式访问​​列表的元素,但我不知道如何。

很抱歉,我是 R 新手。非常感谢您的帮助

【问题讨论】:

    标签: r list dataframe element exists


    【解决方案1】:

    我们可以使用lapply

    unlist(lapply(A, function(x) 'lettuce' %in% x$V1))
    #fruits vegetables 
    # FALSE       TRUE 
    

    【讨论】:

      【解决方案2】:

      尝试使用sapply

      sapply(A, function(x) 'lettuce' %in% x$V1)
      
      #    fruits vegetables 
      #     FALSE       TRUE 
      

      获取名称:

      names(A)[sapply(A, function(x) 'lettuce' %in% x$V1)]
      #[1] "vegetables"
      

      带有purrr 函数。

      library(purrr)
      map_lgl(A, ~'lettuce' %in% .x$V1)
      #    fruits vegetables 
      #     FALSE       TRUE 
      map_int(A, ~'lettuce' %in% .x$V1)
      #    fruits vegetables 
      #         0          1 
      

      【讨论】:

        猜你喜欢
        • 2021-08-19
        • 2019-03-14
        • 2015-03-14
        • 2016-02-23
        • 2021-12-17
        • 2012-11-25
        • 2011-08-02
        • 2018-01-10
        • 2013-12-14
        相关资源
        最近更新 更多