R - How to delete rows before a certain phrase and after a certain phrase in a single column

谁都会走 提交于 2020-06-28 05:11:37

问题


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.

My data is as follows:

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

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.


回答1:


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],]



回答2:


library(tidyverse)
library(stringr)

df2 <- df %>% slice(str_which(type, "GMT")[1]:str_which(type, "GMT")[2])


来源:https://stackoverflow.com/questions/43728632/r-how-to-delete-rows-before-a-certain-phrase-and-after-a-certain-phrase-in-a-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!