On 04-Sep-08 15:33:06, Markus M?hlbacher wrote:> Hello everyone,
> I have a problem using a for-loop to go through a matrix. I want to
> remove all rows with a sum of 0.
> What I do is basically:
>
> for(i in 1:length(data))
> {
> if(sum(add(data[i,]) == 0)
> {
> data <- data[-i,]
> }
> }
>
> I get a error message: "Error in `[.data.frame`(data, i) : undefined
> columns selected", because the length is reduced when removing in the
> if-clause.
>
> How do I make this?
The function rowSums() gives you the row-sums of a matrix, which
you can test for "==0", and carry on from there. Example:
M<-matrix(c(1,2,3,0,-1,-2,-3,1,-2,3,0,1,2,-1),ncol=2)
M
# [,1] [,2]
# [1,] 1 1
# [2,] 2 -2
# [3,] 3 3
# [4,] 0 0
# [5,] -1 1
# [6,] -2 2
# [7,] -3 -1
ix<-which(rowSums(M)==0)
M[-ix,]
# [,1] [,2]
# [1,] 1 1
# [2,] 3 3
# [3,] -3 -1
Hoping this helps!
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 04-Sep-08 Time: 16:49:46
------------------------------ XFMail ------------------------------