[R] Dataframe manipulation question

Rajarshi Guha rajarshi at presidency.com
Wed Oct 6 22:39:53 CEST 2004


On Wed, 2004-10-06 at 16:26, Greg Blevins wrote:
> Hello,
> 
> I have a data frame that has three fields.
> 
> Resp#     ActCode     ProdUsed
> 100          3                  2
> 100          3                  2
> 100          4                  3
> 100          4                  3
> 101          3                  6
> 102          2                  1
> 102          3                  1
> 103          5                  1
> 103          5                  1
> 103          3                  2
> 103          3                  2
> 104          3                  1
> 
> What I seek to do.
> 
> If a row following a row is identical for the fields Resp3 and ActCode, I
> then want to delete one of the two matching rows. Based on this logic, the
> resulting df would look like that shown below.

I'm sure that the Rexperts will provide more elegant solutions but
heres a way which works assuming columns 2 & 3 are numeric so that
diff() works.

If d is the data.frame

> d
   Resp ActCode ProdUsed
1   100       3        2
2   100       3        2
3   100       4        3
4   100       4        3
5   101       3        6
6   102       2        1
7   102       3        1
8   103       5        1
9   103       5        1
10  103       3        2
11  103       3        2
12  104       3        1
>
> y <- which( diff(d[,2]) == 0 & diff(d[,3]) == 0 )
> d[-y,]
   Resp ActCode ProdUsed
2   100       3        2
4   100       4        3
5   101       3        6
6   102       2        1
7   102       3        1
9   103       5        1
11  103       3        2
12  104       3        1

> Resp# ActCode    ProdUsed
> 100      3           2
> 100      4           3
> 101      3           6
> 102      2           1
> 102      3           1
> 103      5           1
> 103      3           2
> 104      3           1

HTH

-------------------------------------------------------------------
Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
-------------------------------------------------------------------
After a number of decimal places, nobody gives a damn.




More information about the R-help mailing list