gpt4 book ai didi

r - 如何让 stopifnot() 在调用列表的缺失 (NULL) 元素时返回错误?

转载 作者:行者123 更新时间:2023-11-28 21:10:12 24 4
gpt4 key购买 nike

使用 stopifnot(),如何测试列表中的元素,同时检查元素本身是否存在?

例如 li 是一个列表,其中包含一个项目。我想确保该项目等于 0。

li <- list()
li$item <- 1
stopifnot(li$item == 0)
# Error: l$x == 0 is not TRUE

返回了一个错误,这就是我想要的。但是,如果我输入错误并输入:

stopifnot(li$tem == 0)

R 不会返回错误。即使该元素不存在于列表中:

li$tem
# NULL

为什么 R 不告诉我在列表中找不到元素“tem”?

li$tem == 0

评估为逻辑(0)。

最佳答案

这里的问题与其说是 stopifnot() 函数,不如说是使用 == 进行比较:

# returns an empty logical vector, not TRUE or FALSE:
li$tem == 0 # logical(0)
# according to ?`==` we should use identical() instead of ==:
identical(li$tem, 0) # returns FALSE
# this now works as it should, i.e. it throws an error:
stopifnot(identical(li$tem, 0))

来自 ?"==":

Do not use == and != for tests, such as in if expressions, where you must get a single TRUE or FALSE. Unless you are absolutely sure that nothing unusual can happen, you should use the identical function instead.

关于r - 如何让 stopifnot() 在调用列表的缺失 (NULL) 元素时返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670060/

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