2

Possible Duplicate:
Select only the first rows for each unique value of a column in R

I have a matrix of the following form:

col1 col2

1    2   
1    2    
1    2   
1    2   
1    2
2    5
2    5
2    5
3    7
3    7
3    7
3    7
3    7
3    7
3    7
3    7
4    2 
4    2 
4    2

I would like to select all the unique rows based on 'col1'.

which in this case would be the first row from each unique value in col1:

subset:

col1   col2
1      2 
2      5
3      7
4      2

Here's what I've tried:

https://dl.dropbox.com/u/22681355/matrix.csv
mat<-read.csv("matrix.csv")
sub<-unique(mat$V1)
subset(mat, mat==c(sub)

It spits out much more than I would expect to get and I get this error mesage:

Warning message: In contacts$V1 == c(g) : longer object length is not a multiple of shorter object length

1
  • Since this is going to be asked anyway, I'll go first: What have you tried? Is there a particular piece of code you're having trouble with?
    – J. Steen
    Dec 12, 2012 at 15:59

1 Answer 1

20

You can use the unique function:

unique(mat$V1) # and not matrix$v1
[1]   44  281 1312

You can also write

unique(mat)

and it will give you unique lines (I tried it on your file).

If you want to select on V1s values, you can do this:

> mat[!duplicated(mat$V1), ]
       X   V1 V2 V3 V4  V5 V6 V7 V8 V9 V10
1   1547   44 14  1  2 100 17  0  0  0   0
23  5385  281 67  2 10 100 10  0  0  0   0
33 17347 1312  1  2  6 100  8  0  0  0   0
5
  • that will not work, see above Dec 12, 2012 at 16:03
  • @user1723765. It would work if you had a matrix like you said you had. It turns out that you have a data.frame. Try unique(as.matrix(mat))
    – GSee
    Dec 12, 2012 at 16:04
  • 2
    this only selects unique values form the first column, but I want the whole row selected for each unique case Dec 12, 2012 at 16:07
  • @user1723765 Yes it does, with mat$v1 not matrix$V1, I used your file.
    – alestanis
    Dec 12, 2012 at 16:10
  • unique must be call with MARGIN = 1 Jun 14, 2019 at 15:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.