本文介绍了返回一个带有 `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)

推荐答案

返回的长度完全由length(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),您也会得到一个向量而不是矩阵输出.因此需要外部 matrix 调用来重置维度.

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:

对于您的示例,看起来像一个简单的 result <- if (a == 1) mat else mat2 就足够了.无需触摸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` 的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:38