[R] merging two specific rows in a DF

jim holtman jholtman at gmail.com
Mon Nov 26 18:49:40 CET 2012


try this:

> x <- read.table(text = "C1      C2      TYPE
+ 10      20      A
+ 33      44      B
+ 66      80      A
+ 111     140     B
+ 144     220     B
+ 300     340     A
+ 380     449     A
+ 455     500     B
+ 510     520     A
+ 540     580     B", header = TRUE, as.is = TRUE)
> # mark successive rows that are different
> x$diff <- c(TRUE, head(x$TYPE, -1) != tail(x$TYPE, -1))
> # create groups where adjacent rows are the same
> x$group <- cumsum(x$diff)
> # now process each group to get min/max
> result <- lapply(split(x, x$group), function(.same){
+     c1Min <- min(.same$C1)
+     c2Max <- max(.same$C2)
+     # put result back into first row and just return its value
+     .same$C1[1L] <- c1Min
+     .same$C2[1L] <- c2Max
+     .same[1,1:3]  # return value drop off the extra columns we added
+     })
> # combine back together
> do.call(rbind, result)
   C1  C2 TYPE
1  10  20    A
2  33  44    B
3  66  80    A
4 111 220    B
5 300 449    A
6 455 500    B
7 510 520    A
8 540 580    B
>
>
>


On Mon, Nov 26, 2012 at 5:24 AM, karthicklakshman
<karthick.lakshman at gmail.com> wrote:
> Hello members,
>
> I have this data frame with 3 columns,
> C1      C2      TYPE
> 10      20      A
> 33      44      B
> 66      80      A
> 111     140     B
> 144     220     B
> 300     340     A
> 380     449     A
> 455     500     B
> 510     520     A
> 540     580     B
>
> Here,  the rows 4 , 5 has type "B" and similarly 6,7 has "A" . I need to
> merge these rows in a way to get the output with unique type, something like
> below, where the lowest value from DF$C1 and  highest value from DF$C2
> corresponding to rows 4,5 are picked.
>
> C1      C2      TYPE
> 10      20      A
> 33      44      B
> 66      80      A
> 111     220     B
> 300     449     A
> 455     500     B
> 510     520     A
> 540     580     B
>
> I Request your kind help..
> Regards,
> karthick
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/merging-two-specific-rows-in-a-DF-tp4650826.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.




More information about the R-help mailing list