0

某行符合条件后如何删除后续行?例如,使用较小的测试数据集:

##test##
testdata<-cbind(c(1,2,3,4), c(5,6,7,8), (c("05/01/2001","01/04/2001", "02/02/2002",     "02/03/2003")))
colnames(testdata)<-c("x", "y", "DOD")
testdata<-as.data.frame(testdata)
testdata$DOD<-as.Date(testdata$DOD, "%m/%d/%Y")
testtemp<-cbind(c(20,30,40), (c("01/01/2001","01/02/2001", "02/02/2002")))
colnames(testtemp)<-c("TMAX", "DATE")

然后我创建一个更大的数据集:

##########LOOP TO GENERATE DATA##########
collapse<-function(data,temp) 
{
newdata<-data[rep(1:nrow(data),each=nrow(temp)),]
newdata$status = 0
newdata<-cbind(newdata, temp)
newdata$status<-ifelse(newdata$DOD == newdata$DATE, 1, 0)
return(newdata)
}

它返回如下内容:

    x y DOD        status TMAX DATE
1   1 5 2001-05-01      0   20 2001-01-01
1.1 1 5 2001-05-01      0   30 2001-01-02
1.2 1 5 2001-05-01      0   40 2002-02-02
2   2 6 2001-01-04      0   20 2001-01-01
2.1 2 6 2001-01-04      0   30 2001-01-02
2.2 2 6 2001-01-04      0   40 2002-02-02
3   3 7 2002-02-02      0   20 2001-01-01
3.1 3 7 2002-02-02      0   30 2001-01-02
3.2 3 7 2002-02-02      1   40 2002-02-02
4   4 8 2003-02-03      0   20 2001-01-01
4.1 4 8 2003-02-03      0   30 2001-01-02
4.2 4 8 2003-02-03      0   40 2002-02-02

我想删除 status=1 之后的所有行,所以在这种情况下是最后三行。

谢谢

4

1 回答 1

4

Use which and subsetting to find the first row which meets your condition and subset it if there is a matching condition otherwise, do nothing...

idx <- which( newdata$DOD == newdata$DATE ) 
if( length( idx ) > 0L ) newdata <- newdata[ seq_len( idx ) , ]
于 2013-08-06T14:53:10.180 回答