为什么R的ifelse语句不能返回向量? [英] Why can't R's ifelse statements return vectors?

查看:309
本文介绍了为什么R的ifelse语句不能返回向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现R的ifelse陈述不时很方便。例如:

I've found R's ifelse statements to be pretty handy from time to time. For example:

ifelse(TRUE,1,2)
# [1] 1
ifelse(FALSE,1,2)
# [1] 2

但我有点困惑通过以下行为。

But I'm somewhat confused by the following behavior.

ifelse(TRUE,c(1,2),c(3,4))
# [1] 1
ifelse(FALSE,c(1,2),c(3,4))
# [1] 3

这是一个高于我的薪资水平的设计选择吗?

Is this a design choice that's above my paygrade?

推荐答案

ifelse 的文档说明:


ifelse 返回与 test 相同的
形状的值,该值填充了从中选择的
元素是

取决于元素
test TRUE FALSE

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的结果。如果您传递更长的测试向量,则会得到更长的时间sults:

Since you are passing test values of length 1, you are getting results of length 1. If you pass longer test vectors, you will get longer results:

> ifelse(c(TRUE, FALSE), c(1, 2), c(3, 4))
[1] 1 4

所以 ifelse 用于测试布尔矢量并返回相同长度的矢量的特定目的,填充元素取自(向量)参数。

So ifelse is intended for the specific purpose of testing a vector of booleans and returning a vector of the same length, filled with elements taken from the (vector) yes and no arguments.

由于函数的名称,这是一个常见的混淆,当你真正想要一个普通的 if(){} else {} 构造时,使用它。

It is a common confusion, because of the function's name, to use this when really you want just a normal if () {} else {} construction instead.

这篇关于为什么R的ifelse语句不能返回向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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