gpt4 book ai didi

r - 如何比较R中的两个列表

转载 作者:行者123 更新时间:2023-12-05 01:36:26 25 4
gpt4 key购买 nike

我有两个要比较的列表。我想看看列表中每个元素的值是否相等。

> m1
[[1]]
integer(0)

[[2]]
[1] 3 4

[[3]]
integer(0)

[[4]]
[1] 1

[[5]]
[1] 2 3 4

> m3
[[1]]
[1] 3

[[2]]
[1] 1 4

[[3]]
[1] 2

[[4]]
[1] 3

[[5]]
[1] 1 4

我希望得到这样的结果:

> Result
[[1]]
[1]
FALSE

[[2]]
[1]
FALSE TRUE

[[3]]
[1]
FALSE

[[4]]
[1]
FALSE

[[5]]
[1]
FALSE FALSE TRUE

如果我尝试应用 m1[1]==m3[1] 或类似的,我会收到消息 Error in m1 == m3 : comparison of these types is not implemented。我做不到这么简单的事情!提前感谢您的帮助。

最佳答案

您可以将 Map(或 mapply)与 %in% 一起使用。

Map(`%in%`, m1, m3)

[[1]]
logical(0)

[[2]]
[1] FALSE TRUE

[[3]]
logical(0)

[[4]]
[1] FALSE

[[5]]
[1] FALSE FALSE TRUE

但是,m1 包含 integer(0),这使得 %in% 返回 logical(0)而不是 FALSE。所以你需要在之后将 logical(0) 转换为 FALSE

res <- Map(`%in%`, m1, m3)
res[lengths(res) == 0] <- FALSE
res

[[1]]
[1] FALSE

[[2]]
[1] FALSE TRUE

[[3]]
[1] FALSE

[[4]]
[1] FALSE

[[5]]
[1] FALSE FALSE TRUE

关于r - 如何比较R中的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62044120/

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