6

I have two matrices:

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

and a parameter

a <- 1

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)
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
Rui
  • 187
  • 1
  • 11

1 Answers1

12

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 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.


Tip 1:

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

Tip 2:

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))

But, this is inconvenient.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • 2
    @zx8754 Tip2, it actually worked perfectly. the problem I exemplified is a (very) simplified version of what I have in hands. I need to choose one matrix from a set of 5, depending on the "a" value. Hence Tip2, thumbs up – Rui Oct 31 '16 at 11:17
  • @Rui Then I would keep all mats in a list, and access as `myList <- list(mat, mat2, mat3, etc); mat.new <- myList[[a]]` – zx8754 Oct 31 '16 at 11:28