R-如何删除单个列中某个特定短语之前和之后的行 [英] R - How to delete rows before a certain phrase and after a certain phrase in a single column

查看:88
本文介绍了R-如何删除单个列中某个特定短语之前和之后的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除某个短语之前的行,然后删除稍后出现的相同(几乎)短语之后的行。我猜想看待它的另一种方式是只保留某个部分开头和结尾的数据。

Hi I would like to delete rows before a certain phrase and then after the same (almost) phrase which appears later on. I guess another way to look at it would be keep only the data from the start and end of a certain section.

我的数据如下:

df <- data.frame(time = as.factor(c(1,2,3,4,5,6,7,8,9,10,11,12,13)), 
                 type = c("","","GMT:yyyy-mm-dd_HH:MM:SS_LT:2016-10-18_06:09:53","(K)","","","","(K)","(K)","","(K)","GMT:yyyy-mm-dd_HH:MM:SS_CAM:2016-10-18_06:20:03",""),
                 names = c("J","J","J","J","J","J","J","J","J","J","J","J","J"))

,我想删除第一个 GMT之前的所有内容:yyyy ... 短语以及第二个 GMT:yyyy ... 短语之后。因此最终产品将是

and I would like to delete everything before the first GMT:yyyy... phrase and after the second GMT:yyyy... phrase. So the end product would be

time   type                                                    names
3      GMT:yyyy-mm-dd_HH:MM:SS_LT:2016-10-18_06:09:53           J
4      (K)                                                      J
5                                                               J
6                                                               J
7                                                               J 
8      (K)                                                      J
9      (K)                                                      J
10                                                              J
11     (K)                                                      J
12     GMT:yyyy-mm-dd_HH:MM:SS_LT:2016-10-18_06:20:03           J

我认为子集可能有用,但这给我带来了问题。

I thought subset might work but it is giving me problems.

推荐答案

使用grep,您可以找到找到您的模式的行的索引:

Using grep, you can locate the indexes of the rows where your pattern is found:

ind=grep("^GMT",df$type)

然后,您只能保留两个索引之间的行:

Then you can keep only the rows between the two indexes:

df=df[ind[1]:ind[2],]

这篇关于R-如何删除单个列中某个特定短语之前和之后的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆