jameselmore
jameselmore

Reputation: 442

Distinguishing a vector from a matrix in R

I'm making a helper function for this project I'm working on in which I need to make percentiles out of a set of data.

In some instances, I'll be percentiling a vector of entries, which is fairly easy. In other instances, I'll be percentiling entries in a matrix.

The processes are similar, but different. I'd like to be able to distinguish what is given as an input (whether it's a vector or a matrix) so I know what operation is appropriate.

I thought about doing something with the dimensions of the input. But dim(*vector*) = NULL, but dim(matrix(1:15, 1,15)) = c(1,15) even though that is debatable to be a vector. So I can't use my first idea of

if(length(dim(objects)) == 2){*A MATRIX*}
else{*A VECTOR*}

I considered that I could just add the condition of min(dim(objects)) > 1 to test for a matrix, but I'm thinking there is probably a better option. (And now I'm here...)

Any thoughts?

Upvotes: 3

Views: 111

Answers (2)

IRTFM
IRTFM

Reputation: 263352

Why not use prop.table for the operations? You can get either row or column proportions and if you wnat percentiles you can multiply by 100 and round to the desired accuracy

> m <- matrix(1:9, 3)
> prop.table(m, 1)
           [,1]      [,2]      [,3]
[1,] 0.08333333 0.3333333 0.5833333
[2,] 0.13333333 0.3333333 0.5333333
[3,] 0.16666667 0.3333333 0.5000000
> prop.table(m,2)
          [,1]      [,2]      [,3]
[1,] 0.1666667 0.2666667 0.2916667
[2,] 0.3333333 0.3333333 0.3333333
[3,] 0.5000000 0.4000000 0.3750000

> round(100*prop.table(m, 1), 2) # rounded row percentages
      [,1]  [,2]  [,3]
[1,]  8.33 33.33 58.33
[2,] 13.33 33.33 53.33
[3,] 16.67 33.33 50.00

Upvotes: 2

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

Seems like you want to ignore any dimension that only has one level, so drop would be appropriate:

if(is.null(dim(drop(x)))) {
  # do vector stuff
} else {
  # do matrix/array stuff
}

Upvotes: 5

Related Questions