[R] how to remove one row at a time from a matrix keeping its nrow consistent

David Winsemius dwinsemius at comcast.net
Sat Apr 17 20:53:30 CEST 2010


On Apr 17, 2010, at 2:25 PM, <mauede at alice.it> wrote:

> After some headache with debugging my script, I finally isolated the  
> problem taht I am going to illustrate in the following example.
> I expected matrix nrow to decrease consistently till 1. Instead,  
> when the matrix is left with one row only, its nrow jumps to 2  
> because the matrix
> gets transposed. How come ?

Because you did not use drop=FALSE? (And I think it's a FAQ.)

 > #REMOVE ROW-1 OUT OF 3
 > B <- as.matrix(B[-1,,drop=FALSE])
 > B
  [,1] [,2]
     3    4
     5    6
 > #REMOVE ROW-2 OUT OF 3
 > B <- as.matrix(B[-1, ,drop=FALSE])
 > B
  [,1] [,2]
     5    6

 > nrow(B)
[1] 1


> Thank you,
> Maura
>
>> B <- c(1,2)
>> B <- rbind(B,c(3,4))
>> B <- rbind(B,c(5,6))
>> B
>  [,1] [,2]
> B    1    2
>     3    4
>     5    6
>> dim(B)
> [1] 3 2
>> nrow(B)
> [1] 3
>>
>> #REMOVE ROW-1 OUT OF 3
>> B <- as.matrix(B[-1,])
>> B
> [,1] [,2]
>    3    4
>    5    6
>> dim(B)
> [1] 2 2
>> nrow(B)
> [1] 2
>>
>> #REMOVE ROW-2 OUT OF 3
>> B <- as.matrix(B[-1,])
>> B
>     [,1]
> [1,]    5
> [2,]    6
>> dim(B)
> [1] 2 1
>> nrow(B)
> [1] 2
>
>
>
> tutti i telefonini TIM!
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list