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

Ista Zahn istazahn at gmail.com
Sat Apr 17 20:43:14 CEST 2010


On Sat, Apr 17, 2010 at 7: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 the one-row matrix gets reduced to a vector:

> B <- matrix(1:4, nrow = 2, byrow = TRUE)
> class(B)
[1] "matrix"
> B1 <- B[-1,]
> class(B1)
[1] "integer"

and as.matrix applied to a vector produces a one-column matrix (see ?as.matrix).

> 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.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org



More information about the R-help mailing list