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
353 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 Reply

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.


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

...