简体   繁体   English

根据条件删除R中的行

[英]Deleting row in R based on meeting conditions

I am reading in a very large dataset using read.table. 我正在使用read.table读取非常大的数据集。 Once I've read the data in, I want to keep only those records that fall in a certain lat/lon region. 读完数据后,我只想保留属于某个经纬度区域的那些记录。 So basically I want to define upper and lower bounds on $Lat and $Lon, and discard all other rows. 所以基本上我想定义$ Lat和$ Lon的上限和下限,并丢弃所有其他行。 I'm sure this is a fairly easy operation, but I am new to R coding and want to make sure I find the most elegant approach. 我确信这是一个相当容易的操作,但是我是R编码的新手,并希望确保找到最优雅的方法。 Here is my code to read in the data: 这是我要读取数据的代码:

#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")]

}   

Instead of that last part where I keep all track points, I'd like to only keep lat between 30 and 35, and lon between 128 and 140. 而不是我保留所有跟踪指标的最后一部分,我只想将经度保持在30到35之间,将lon保持在128到140之间。

I think what you're looking for is row-selection rather than row-deletion. 我认为您正在寻找的是行选择而不是行删除。 You can select rows by using AND gate logic with your four criteria: 您可以通过对四个条件使用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)

This tells your data frame to select rows that meet all of the four criteria. 这告诉您的数据框选择满足所有四个条件的行。

Update : As requested, here is the same code in 'subset' form: 更新 :根据要求,以下是“子集”形式的相同代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM