[R] Removal of columns from matrix where all values of the column are identical.
Ben Bolker
bbolker at gmail.com
Sat Jan 26 03:38:36 CET 2013
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 ...
More information about the R-help
mailing list