代码部分:
# reproduce your data, igoring the last 2 columns
c1 <- c(1:12)
c2 <- rep(5,12)
c2[7:8] <- 6
c3 <- c(23,23,21,20,20,19,rep(16,4),15,15)
c4 <- rep(101100,12)
c4[1:2] <- 101200
c4[c(7,11,12)] <- 105800
c4[8] <- 101700
data <- matrix(c(c1,c2,c3,c4),ncol=4)
# selection procedure
c4sel <- unique(data[,4])
vecf <- NULL # initiate final selected data in vector form
for(i in 1:length(c4sel)){
sel1 <- data[data[,4]==c4sel,]
if (!is.vector(sel1)){
sel2 <- sel1[sel1[,3]==max(sel1[,3]),]
if (!is.vector(sel2)){
sel3 <- sel2[sel2[,1]==min(sel2[,1]),]
vecf <- c(vecf,sel3)
} else {
vecf <- c(vecf,sel2)
}
} else {
vecf <- c(vecf,sel1)
}
}
dataf <- matrix(vecf,ncol=4,byrow=T)
运行结果:
> # reproduce your data, igoring the last 2 columns
> c1 <- c(1:12)
> c2 <- rep(5,12)
> c2[7:8] <- 6
> c3 <- c(23,23,21,20,20,19,rep(16,4),15,15)
> c4 <- rep(101100,12)
> c4[1:2] <- 101200
> c4[c(7,11,12)] <- 105800
> c4[8] <- 101700
> data <- matrix(c(c1,c2,c3,c4),ncol=4)
> data
[,1] [,2] [,3] [,4]
[1,] 1 5 23 101200
[2,] 2 5 23 101200
[3,] 3 5 21 101100
[4,] 4 5 20 101100
[5,] 5 5 20 101100
[6,] 6 5 19 101100
[7,] 7 6 16 105800
[8,] 8 6 16 101700
[9,] 9 5 16 101100
[10,] 10 5 16 101100
[11,] 11 5 15 105800
[12,] 12 5 15 105800
>
> # selection procedure
> c4sel <- unique(data[,4])
> vecf <- NULL # initiate final selected data in vector form
> for(i in 1:length(c4sel)){
+ sel1 <- data[data[,4]==c4sel,]
+ if (!is.vector(sel1)){
+ sel2 <- sel1[sel1[,3]==max(sel1[,3]),]
+ if (!is.vector(sel2)){
+ sel3 <- sel2[sel2[,1]==min(sel2[,1]),]
+ vecf <- c(vecf,sel3)
+ } else {
+ vecf <- c(vecf,sel2)
+ }
+ } else {
+ vecf <- c(vecf,sel1)
+ }
+ }
> dataf <- matrix(vecf,ncol=4,byrow=T)
> dataf
[,1] [,2] [,3] [,4]
[1,] 1 5 23 101200
[2,] 3 5 21 101100
[3,] 7 6 16 105800
[4,] 8 6 16 101700
>