[R] merging two specific rows in a DF
arun
smartpink111 at yahoo.com
Mon Nov 26 20:24:49 CET 2012
HI,
Just a modification of Rui's solution:
x1<-within(x,TYPE<-as.character(TYPE))
group<-cumsum(c(TRUE,x1$TYPE[-1]!=x1$TYPE[-length(x1$TYPE)]))
res<-as.data.frame(do.call(rbind,lapply(split(x1,group),function(x) c(C1=min(x[,1]),C2=max(x[,2]),TYPE=x[,3][1]))),stringsAsFactors=FALSE)
res[,-3]<-sapply(res[,-3],as.numeric)
res
# 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
A.K.
----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: karthicklakshman <karthick.lakshman at gmail.com>
Cc: r-help at r-project.org
Sent: Monday, November 26, 2012 12:37 PM
Subject: Re: [R] merging two specific rows in a DF
Hello,
Try the following.
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)
x
fun <- function(x){
mn <- which.min(x$C1)
mx <- which.max(x$C2)
c(C1 = x$C1[mn], C2 = x$C2[mx], TYPE = x$TYPE[1])
}
idx <- seq_len(nrow(x))[-1]
idx2 <- cumsum(c(FALSE, x$TYPE[idx - 1] != x$TYPE[idx]))
y <- do.call(rbind, lapply(split(x, idx2), fun))
rownames(y) <- seq_len(nrow(y))
y
Hope this helps,
Rui Barradas
Em 26-11-2012 10:24, karthicklakshman escreveu:
> 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.
______________________________________________
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.
More information about the R-help
mailing list