简体   繁体   English

如何删除R中的所有行,直到某个值

[英]How to delete all rows in R until a certain value

I have a several data frames which start with a bit of text. 我有几个数据框,从一些文本开始。 Sometimes the information I need starts at row 11 and sometimes it starts at row 16 for instance. 有时我需要的信息从第11行开始,有时它从第16行开始。 It changes. 它改变。 All the data frames have in common that the usefull information starts after a row with the title "location". 所有数据帧的共同之处在于有用信息在具有标题“位置”的行之后开始。

I'd like to make a loop to delete all the rows in the data frame above the useful information (including the row with "location"). 我想循环删除有用信息上方数据框中的所有行(包括“location”行)。

I'm guessing that you want something like this: 我猜你想要这样的东西:

readfun <- function(fn,n=-1,target="location",...) {
   r <- readLines(fn,n=n)
   locline <- grep(target,r)[1]
   read.table(fn,skip=locline,...)
}

This is fairly inefficient because it reads the data file twice (once as raw character strings and once as a data frame), but it should work reasonably well if your files are not too big. 这是相当低效的,因为它读取数据文件两次(一次作为原始字符串,一次作为数据帧),但如果您的文件不是太大,它应该工作得相当好。 (@MrFlick points out in the comments that if you have a reasonable upper bound on how far into the file your target will occur, you can set n so that you don't have to read the whole file just to search for the target.) (@MrFlick在评论中指出,如果你对目标发生的距离有一个合理的上限,你可以设置n这样你就不必只是为了搜索目标而读取整个文件。 )

I don't know any other details of your files, but it might be safer to use "^location" to identify a line that begins with that string, or some other more specific target ... 我不知道您的文件的任何其他细节,但使用"^location"来识别以该字符串开头的行或其他更具体的目标可能更安全......

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

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