gpt4 book ai didi

r - if-else 与带列表的 ifelse

转载 作者:行者123 更新时间:2023-12-04 01:34:00 24 4
gpt4 key购买 nike

为什么 if-else 构造和函数 ifelse() 的行为不同?

mylist <- list(list(a=1, b=2), list(x=10, y=20))

l1 <- ifelse(sum(sapply(mylist, class) != "list")==0, mylist, list(mylist))

l2 <-
if(sum(sapply(mylist, class) != "list") == 0){ # T: all list elements are lists
mylist
} else {
list(mylist)
}

all.equal(l1,l2)
# [1] "Length mismatch: comparison on first 1 components"

最佳答案

从 ifelse 文档:

 ‘ifelse’ returns a value with the same shape as ‘test’ which is
filled with elements selected from either ‘yes’ or ‘no’ depending
on whether the element of ‘test’ is ‘TRUE’ or ‘FALSE’.

所以你的输入长度为 1,所以输出被截断为长度 1。

您还可以通过一个更简单的示例来说明这一点:
ifelse(TRUE, c(1, 3), 7)
# [1] 1

关于r - if-else 与带列表的 ifelse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449184/

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