根据会议条件删除R中的行

时间:2013-05-22 16:32:05

标签: r row conditional delete-row

我正在使用read.table读取一个非常大的数据集。一旦我读入数据,我想只保留那些属于某个纬度/经度区域的记录。所以基本上我想在$ Lat和$ Lon上定义上限和下限,并丢弃所有其他行。我确信这是一个相当简单的操作,但我是R编码的新手,并希望确保找到最优雅的方法。这是我在数据中读取的代码:

#trackfilenums=1:96   #these are the legs of the track files
trackfilenums=1

for(i in trackfilenums){

print(paste(i, 96, Sys.time(), sep=" : "))
track.data.file <- paste('input/track_param/track_param_',zpad(i,4),'.txt', sep="")
track.data <- read.table( track.data.file ,fill=TRUE,as.is=TRUE,skip=1)
sel <- !is.na(track.data[,9])
track.data <- track.data[sel,]
colnames(track.data) <- c("ID", "Hr", "Lon", "Lat", "UT", "VT", "LandFlag", "ET", "CP", "Penv", "Rmax", "Vmax", "X1", "N", "EOF1", "EOF2", "EOF3", "EOF4", "Angle", "MPI", "Filling.alpha", "Filling.beta", "Filling.gamma")

## keep all points 
track.data<-track.data[,c("ID", "Hr", "Lon", "Lat", "UT", "VT", "LandFlag", "ET", "CP", "Penv", "Rmax", "Vmax", "X1")]

}   

而不是我保留所有跟踪点的最后一部分,我只想保持介于30和35之间的纬度,并且介于128和140之间。

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找的是行选择而不是行删除。您可以使用AND门逻辑选择行,并使用以下四个条件:

# Note that I am using the 'attach' function to
# make things a little easier to read.
attach(track.data)
track.data[Lat >= 30 & Lat <=35 & Lon >=128 & Lon <= 140,]
detach(track.data)

这会告诉您的数据框选择符合所有四个条件的行。

更新:根据要求,以下是&#39;子集&#39;中的相同代码。形式:

subset(track.data, Lat >= 30 & Lat <=35 & Lon >=128 & Lon <= 140)