if-else vs ifelse with lists [英] if-else vs ifelse with lists

查看:141
本文介绍了if-else vs ifelse with lists的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么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表现相同,而R来自编程传统。 R的隐式for循环内置于许多矢量化函数中(包括 ifelse )。

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, whereas R came from a programming tradition. R's implicit for-loops are built in to the many vectorized functions (including ifelse).

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 vs ifelse with lists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆