Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

r - Return a matrix with `ifelse`

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...