[R] remove elements from matrix
Ulrich Staudinger
ustaudinger at gmail.com
Fri Sep 30 12:30:46 CEST 2011
Am 30.09.2011 11:30, schrieb Alaios:
> Dear all,
> I have a numeric vector that contains indices.
> I also have two matrices of [1,m] dimension and of [m,n] dimension.
>
> I want for every indexto remove the current element from the [1,m] vector an the row from the [m,n] matrix.
> How I can do that efficiently in R? So to say not have a for loop getting parameter after parameter and then removing row by row from the vector and the matrix.
>
>
This should get you there ...
> indexVec = c(2,3)
> indexVec
[1] 2 3
> mat1 = matrix(rnorm(4),1,4)
> mat1
[,1] [,2] [,3] [,4]
[1,] -0.4535787 -0.09076038 1.156931 -0.9116866
>
> mat2 = matrix(rnorm(4),4,1)
> mat2
[,1]
[1,] -1.4346468
[2,] -0.1764882
[3,] 0.8840969
[4,] -0.8722242
>
> trueFalseIndex = rep(FALSE, length(mat1))
> trueFalseIndex
[1] FALSE FALSE FALSE FALSE
> trueFalseIndex[indexVec] = TRUE
> trueFalseIndex
[1] FALSE TRUE TRUE FALSE
> mat1[!trueFalseIndex]
[1] -0.4535787 -0.9116866
>
I assume you can make the transfer to filter mat2 yourself ...
Regards,
Ulrich
More information about the R-help
mailing list