replacing duplicate rows

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

replacing duplicate rows

cassie jones
Hi all,

I have a matrix which looks like the following,

x=matrix(c(1,2,3,4,3,5,4,6,4,9),5,2,byrow=T)

Now, I want to replace the 2nd columns of those 4 rows which have duplicate
entries in the 1st column. For example, x[2,1]=x[3,1]=3 and I want to
replace x[3,2] by x[2,2]. Similarly, I want to replace x[5,2] with x[4,2],
which means that for duplicate entries in the 1st column, I want to replace
the corresponding entries in the 2nd column with its 1st entry of the
duplicate row.

Can anybody help me in this regard?

Thanks,
Cassie

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] 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.
Reply | Threaded
Open this post in threaded view
|

Re: replacing duplicate rows

Peter Ehlers
On 2011-07-21 09:59, cassie jones wrote:

> Hi all,
>
> I have a matrix which looks like the following,
>
> x=matrix(c(1,2,3,4,3,5,4,6,4,9),5,2,byrow=T)
>
> Now, I want to replace the 2nd columns of those 4 rows which have duplicate
> entries in the 1st column. For example, x[2,1]=x[3,1]=3 and I want to
> replace x[3,2] by x[2,2]. Similarly, I want to replace x[5,2] with x[4,2],
> which means that for duplicate entries in the 1st column, I want to replace
> the corresponding entries in the 2nd column with its 1st entry of the
> duplicate row.

Try match():

  idx <- match(x[,1], x[,1])
  x[,2] <- x[idx,2]

Peter Ehlers

>
> Can anybody help me in this regard?
>
> Thanks,
> Cassie
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] 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.

______________________________________________
[hidden email] 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.