lodeg
lodeg

Reputation: 45

R - Merge multiple rows of a matrix that presents a common column position of row-elements?

I want to merge multiple rows in one row where these rows have the same column element position.

Input:

      one two three four five
[1,]   1   1    1    0     0
[2,]   2   2    2    0     0
[3,]   0   0    3    3     3
[4,]   4   4    4    0     0
[5,]   0   0    5    5     5
[6,]   6   0    6    0     6

The output matrix must be like this one:

       one two three four five
[1,]   1   1    1    0     0
[2,]   0   0    3    3     3
[3,]   6   0    6    0     6

Note that the merged rows presents the values that are minimum betweens the merged rows.

Upvotes: 2

Views: 172

Answers (1)

Marat Talipov
Marat Talipov

Reputation: 13304

Given a matrix m, you can do:

m[!duplicated(m==0),]
#     one two three four five
#[1,]   1   1     1    0    0
#[3,]   0   0     3    3    3
#[6,]   6   0     6    0    6

m==0 returns a logical matrix, duplicated returns a logical vector indicating duplicate rows, which is used to subset matrix m.

Upvotes: 5

Related Questions