Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

if statement - Struggling with the ifelse function in R

Can someone please explain me what I am doing wrong. I don't understand the behaviour of the ifelse function in R. I expected that the ifelse function would return the whole list ids_match. However, these are the results I get with RStudio Version 1.3.1093 in the Console Window:

 cond1 = FALSE
 cond2 = FALSE
 cond3 = TRUE
 ids_match = list(1, 2, 3)

ifelse(cond1 & cond2 & cond3, ids_match[1], ids_match)

[[1]] [1] 1

ifelse(TRUE, ids_match[1], ids_match)

[[1]] [1] 1

ifelse(FALSE, ids_match[1], ids_match)

[[1]] [1] 1

ifelse(FALSE, "TRUE", "FALSE")

[1] "FALSE"

ifelse(TRUE, "TRUE", "FALSE")

[1] "TRUE"`

question from:https://stackoverflow.com/questions/65933469/struggling-with-the-ifelse-function-in-r

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

1 Answer

0 votes
by (71.8m points)

According to ?ifelse:

Usage: ifelse(test, yes, no)

Description: ‘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’.

Now, since (cond1 & cond2 & cond3) is a single boolean variable (i.e. length(cond1 & cond2 & cond3) == 1), your response will also have length of 1.

Also see related discussion here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...