【问题标题】:which function for filtering TRUE/FALSE in a list in R哪个函数用于过滤 R 列表中的 TRUE/FALSE
【发布时间】:2021-04-16 15:34:38
【问题描述】:

我有两个列表:

test1
$`0`
[1] "Mean relative difference: 0.005401506 in referenceBasedPrice."

$`1`
[1] TRUE

> test2
$`0`
[1] "Mean relative difference: 0.005401506 in referenceBasedPrice."

$`1`
[1] "some text"

我只想保留那些不是TRUE 的列表元素,我为此写了:

> test1 = test1[-which(sapply(test1, isTRUE))]
> test1
$`0`
[1] "Mean relative difference: 0.005401506 in referenceBasedPrice."

但它似乎在第二个列表上无法正常工作,其中不包含任何 TRUE:

> test2 = test2[-which(sapply(test2, isTRUE))]
> test2
named list()

为什么它不适用于列表test2

【问题讨论】:

    标签: r list datatable subset


    【解决方案1】:

    试试这个:

    #Data
    test1 <- list(`0`="Mean relative difference: 0.005401506 in referenceBasedPrice.",
                  `1`=T)
    #Code
    lapply(test1, function(x) x[!isTRUE(x)])
    

    或者这个:

    #Code 2
    unlist(lapply(test1, function(x) x[!isTRUE(x)]))
    

    请注意,您有列表而不是数据框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2012-04-06
      相关资源
      最近更新 更多