if-else vs ifelse with lists

Ryo*_*ogi 11 if-statement r

为什么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"
Run Code Online (Sandbox Code Playgroud)

Das*_*son 13

从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’.
Run Code Online (Sandbox Code Playgroud)

因此,您的输入长度为1,因此输出被截断为长度1.

您还可以通过一个更简单的示例来看到这个说明:

ifelse(TRUE, c(1, 3), 7)
# [1] 1
Run Code Online (Sandbox Code Playgroud)


42-*_*42- 12

if ( cond) { yes } else { no }是一种控制结构.它旨在实现编程叉而不是处理序列.我想很多人都来自SPSS或SAS,他们的作者选择"IF"在他们的DATA或TRANSFORM函数中实现条件赋值,因此他们期望R表现相同,而R来自编程传统.R的隐式for循环内置于许多向量化函数(包括ifelse)中.

ifelse采用一个表达式,构建一个逻辑值向量作为其第一个参数.第二个和第三个参数需要是相等长度的向量,并且要么选择第一个,要么选择第二个.这类似于IF具有隐式行 - 操作模式的SPSS/SAS 命令.