gpt4 book ai didi

r - 仅 append 不是 "TRUE"的列表元素

转载 作者:行者123 更新时间:2023-12-03 23:26:17 24 4
gpt4 key购买 nike

我有三个列表:test1 , test2 , test3 :

test1 <- list(`0` = "text", `1` = T)
test2 <- list(`0` = "text", `1` = "text")
test3 <- list(`0` = T, `1` = T)
在这些列表中,我只想保留 的信息不是 TRUE .为此,我正在使用 lapply:
test1 <- lapply(test1, function(x) x[!isTRUE(x)])
test2 <- lapply(test2, function(x) x[!isTRUE(x)])
test3 <- lapply(test3, function(x) x[!isTRUE(x)])
现在,我想将 test1、test2 和 test3 append 到具有同名列表元素的空列表中。但是,我只想 append 文本输入。文本可能会有所不同,无法通过字符匹配来做到这一点。我目前得到:
$test1
$test1$`0`
[1] "text"

$test1$`1`
logical(0)


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
$test3$`0`
logical(0)

$test3$`1`
logical(0)
想要的结果是:
$test1
$test1$`0`
[1] "text"


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
NULL
我怎样才能避免收到 logical(0)并获得我想要的结果?

最佳答案

这几乎给出了想要的结果:

lapply(
list(test1=test1, test2=test2, test3=test3),
function(x){
Filter(Negate(isTRUE), x)
}
)
这给出:
$test1
$test1$`0`
[1] "text"


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
named list()
唯一的区别是 named list()test3 .但这种行为可能取决于 R 版本(我使用的是 3.6.3)。
获取 NULL ,将此代码应用于此新列表:
lapply(newlist, function(x) if(length(x)) x)

关于r - 仅 append 不是 "TRUE"的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65681274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com