# r - Check if all rows are the same in a matrix

I'm looking to see if `sample(..., replace=T)` results in sampling the same row `n` times. I see the `duplicated` function checks if elements are repeated by returning a logical vector for each index, but I need to see if one element is repeated `n` times (single boolean value). What's the best way to go about this?

Here's just an example. Some function on this matrix should return `TRUE`

``t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))[,1] [,2][1,] 4 5[2,] 4 5[3,] 4 5[4,] 4 5[5,] 4 5[6,] 4 5[7,] 4 5[8,] 4 5``

Here is one solution that works to produce the true/false result you are looking for:

``````m <- t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
apply(m, 2, function(x) length(unique(x)) == 1)
[1] TRUE TRUE

m <- rbind(m, c(4, 6))
apply(m, 2, function(x) length(unique(x)) == 1)
[1]  TRUE FALSE
``````

If you want a single boolean value saying if all columns have unique values, you can do:

``````all(apply(m, 2, function(x) length(unique(x)) == 1) == TRUE)
[1] FALSE
``````

Think I've got my solution.

``````B <- t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
length(table(B)) == ncol(B)
[1] TRUE
B <- rbind(B,c(4,6)) # different sample
length(table(B)) == ncol(B)
[1] FALSE
``````

We could also replicate the first row, compare with the original matrix, get the `colSums` and check whether it is equal to `nrow` of 'm'

``````colSums(m[1,][col(m)]==m)==nrow(m)
[1] TRUE TRUE
``````

Or another option would be to check the variance

``````!apply(m, 2, var)
#[1] TRUE TRUE
``````