if-else vs ifelse with lists

后端 未结 3 2299
旧时难觅i
旧时难觅i 2020-11-28 15:19

Why do the if-else construct and the function ifelse() behave differently?

mylist <- list(list(a=1, b=2), list(x=10, y=20))

l1 <- ifelse(sum(sapply(my         


        
3条回答
  •  无人及你
    2020-11-28 15:42

    From the ifelse documentation:

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

    So your input has length one so the output is truncated to length 1.

    You can also see this illustrated with a more simple example:

    ifelse(TRUE, c(1, 3), 7)
    # [1] 1
    

提交回复
热议问题