0

When I use ifelse function with is.table or is.matrix I get unwanted results. Whereas if I use an if statement I get the result I want. Example below.

x <- table(state.division, state.region)

colSums(x) ## What I am supposed to get in the code below
rowSums(x) ## Same

ifelse(is.table(x), colSums(x), 0) ## Get only the first element of colSums(x)
ifelse(is.matrix(x), apply(x, 2, sum), 0) ## Tried with apply instead but same results
ifelse(is.matrix(x), rowSums(x), 0) ## Same for rowSums
ifelse(is.table(x), apply(x, 1, sum), 0)

if (is.table(x)) colSums(x) ## All fine

Anybody know what's going on?

user3631369
  • 329
  • 1
  • 12
  • 1
    (1) If your logic is always a single logical, then always use `if`, not `ifelse`. (2) `ifelse` has some [drawbacks](https://stackoverflow.com/q/6668963/3358272). (3) It will never return a dimensioned object properly, it is intended for vectors, not arrays or such, and if the lengths are compatible, will likely only return a single element of the vector (for each conditional). – r2evans Feb 01 '21 at 15:07
  • 1
    Said differently: `ifelse` is meant for vectors, where each of the arguments has the same length (usually greater than 1). For instance, `ifelse(c(T,F,T), 1:3, 11:13)` should return `c(1,12,3)`, since the `T`'s return the *corresponding indices* from the second argument (`1:3`), and the `F`'s return the indices from the third argument (`11:13`). It drops classes and dimensions, always returning a vector. But it's always a piece-wise return. If you want the IF-clause to return something more than length-1 from each of your yes/no args, use `if` and a length-1 conditional. – r2evans Feb 01 '21 at 15:12
  • Thanks! I've read the documentation afterwards... and looks like this is what is meant by "_A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no._" – user3631369 Feb 02 '21 at 08:12

0 Answers0