[R] Confusing fori or ifelse result in matrix manipulation

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Mon Apr 25 10:49:22 CEST 2022


В Sun, 24 Apr 2022 17:05:55 +0200
Uwe Freier <uwe using freier.de> пишет:

> ifelse(x[i] == 0, A[,i], 0)

Hint: what does ifelse return instead of a vector of length nrow(A)?

Since you're checking conditions of length 1, you can safely use `if
(x[i] == 0) A[,i] else 0` here, or you can transform the `x` vector
into a boolean matrix of the correct shape to guide the substitution:

X <- matrix(as.logical(x), nrow(A), ncol(A), byrow = TRUE)
ifelse(X, 0, A)

-- 
Best regards,
Ivan



More information about the R-help mailing list