返回带有“ifelse”的矩阵 [英] Return a matrix with `ifelse`

查看:172
本文介绍了返回带有“ifelse”的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵:

mat <- matrix(1:6, 2, 3)
mat2 <- matrix(1:2, 2, 3)

和参数

a <- 1

使用 ifelse ,当 a 是某个值时,是否可以返回矩阵?
我正在使用的代码不起作用。例如:

using ifelse, is it possible to return a matrix when a is a certain value? the code that I am using, does not work. For example:

mat.new <- ifelse(a == 1, mat, mat2)


推荐答案

返回的长度完全由长度决定( a == 1)。另请参阅带有?ifelse 的帮助文件。您的代码只返回一个值。

The length of the return is completely decided by length(a == 1). See also the helpfile with ?ifelse. Your code will only return a single value.

ifelse 目标向量输入/输出。即使你得到正确的长度,比如说: ifelse(rep(TRUE,6),mat,mat2),你得到一个向量而不是矩阵输出。所以外部矩阵调用重置维度是必要的。

ifelse targets vector input / output. Even if you get the length correct, say: ifelse(rep(TRUE, 6), mat, mat2), you get a vector rather than a matrix output. So an outer matrix call to reset dimension is necessary.

提示1:

对于您的示例,看起来像一个简单的结果< - if(a == 1) mat else 就足够了。无需触摸 ifelse

For your example, looks like a simple result <- if (a == 1) mat else mat2 is sufficient. No need to touch ifelse.

提示2:

要求 ifelse 返回矩阵并非不可能,但你必须用列表来保护它(记住列表是一个向量):

It is not impossible to ask ifelse to return a matrix, but you have to protect it by a list (remember a list is a vector):

ifelse(TRUE, list(mat), list(mat2))

但是,这很不方便。

这篇关于返回带有“ifelse”的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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