Reputation: 45
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
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