Skip to content
Prev 316195 / 398506 Next

Removal of columns from matrix where all values of the column are identical.

Hi,

I've been trying to work this out how it works, I'm still not totally sure but seems to me it subsets the matrix according to whether each column returns all TRUE, to not being the same values when you compare the column[-1] and the column[-length(column)], essentially siding the column against itself and making comparison? It seems that it also removed columns with any repeated values, rather than columns in which all values are the same:

testm<-matrix(nrow=5, ncol=5)
testm[,1] <- c(1,2,3,4,5)
testm[,2] <- c(3,3,3,3,3)
testm[,3] <- c(3,3,3,4,3)
testm[,4] <- c(5,4,3,2,1)
testm[,5] <- c(1,2,3,4,4)
testm

test3 <- testm[,apply(testm,2,function(x) all(c(TRUE,x[-length(x)]!=x[-1])))]
test3

test3
? ? ?[,1] [,2]
[1,] ? ?1 ? ?5
[2,] ? ?2 ? ?4
[3,] ? ?3 ? ?3
[4,] ? ?4 ? ?2
[5,] ? ?5 ? ?1

Thanks,
Ben W.