Benjamin Ward (ENV <B.Ward <at> uea.ac.uk> writes: > I'd like to write a piece of code which will remove columns from a matrix, if the column contains only one > value, say every value in the column is a "3": > > Matrix <- matrix(NA, nrow=5, ncol=4) > Matrix[,1] <- c(1,2,3,4,5) > Matrix[,2] <- c(3,3,3,3,3) > Matrix[,3] <- c(5,4,3,2,1) > Matrix[,4] <- c(5,1,4,3,2) > > [,1] [,2] [,3] [,4] > [1,] 1 3 5 5 > [2,] 2 3 4 1 > [3,] 3 3 3 4 > [4,] 4 3 2 3 > [5,] 5 3 1 2
I think you want Matrix[, apply(Matrix,2,function(x) { length(unique(x))>1 ) } ] The anonymous function tests whether there is more than one unique value. apply() runs it on every column and returns a logical vector. The [ , ] indexing selects the corresponding columns ... ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.