if-else vs ifelse with lists

后端 未结 3 2286
旧时难觅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:54

    if ( cond) { yes } else { no } is a control structure. It was designed to effect programming forks rather than to process a sequence. I think many people come from SPSS or SAS whose authors chose "IF" to implement conditional assignment within their DATA or TRANSFORM functions and so they expect R to behave the same, whereas R came from a programming tradition. R's implicit for-loops are built in to the many vectorized functions (including ifelse).

    ifelse takes an expression that builds a vector of logical values as its first argument. The second and third arguments need to be vectors of equal length and either the first of them or the second gets chosen. This is similar to the SPSS/SAS IF commands which have an implicit by-row mode of operation.

提交回复
热议问题