问题描述
为什么 if-else 结构和函数 ifelse() 的行为不同?
Why do the if-else construct and the function ifelse() behave differently?
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"
推荐答案
if ( cond) { yes } else { no }
是一个控制结构.它旨在影响编程分支而不是处理序列.我认为很多人来自 SPSS 或 SAS,他们的作者选择了IF".在他们的 DATA 或 TRANSFORM 函数中实现条件赋值,因此他们希望 R 的行为相同.SA 和 SPSS 在那里的数据步骤中都有隐含的 FOR 循环.而 R 来自编程传统.R 的隐式 for 循环内置于许多向量化函数(包括 ifelse
)中.lapply/sapply 函数是实现大多数顺序处理的更精明的方法,尽管它们在执行滞后变量访问方面没有成功,特别是如果有任何随机化特征的效果"累积处理.
if ( cond) { yes } else { no }
is a control structure. It was designed to effect programming forks rather than to process a sequence. I think many people come from SPSS or SAS whose authors chose "IF" to implement conditional assignment within their DATA or TRANSFORM functions and so they expect R to behave the same. SA and SPSS both have implicit FOR-loops in there Data steps. Whereas R came from a programming tradition. R's implicit for-loops are built in to the many vectorized functions (including ifelse
). The lapply/sapply fucntions are the more Rsavvy way to implement most sequential processing, although they don't succeed at doing lagged variable access, especially if there are any randomizing features whose "effects" get cumulatively handled.
ifelse
将构建逻辑值向量的表达式作为其第一个参数.第二个和第三个参数需要是等长的向量,并且选择第一个或第二个.这类似于具有隐式按行操作模式的 SPSS/SAS IF
命令.
ifelse
takes an expression that builds a vector of logical values as its first argument. The second and third arguments need to be vectors of equal length and either the first of them or the second gets chosen. This is similar to the SPSS/SAS IF
commands which have an implicit by-row mode of operation.
这篇关于if-else 与带列表的 ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!