仅保留具有特定字符串的行上方的行

Keep only rows above row with certain string

我是新手,所以请多关照:)

我在 R 中使用 tidyverse 包。

我有一个数据帧列表。在每个数据框中,我只想保留第一行上方第一列中具有特定字符串(在本例中为三个星号)的行。在附带的示例中,我想保留第 21 行以上的所有行(即第一列中第一次遇到“***”)。我该怎么做?

这是使用 dplyr 中的 filter 执行此操作的一种方法。基本上,您要在列循环中查找“***”与 grepl 的匹配项。这将为您提供一个逻辑向量。在我的示例中,FALSE,FALSE,FALSE,TRUE, TRUE。在此向量上使用 cumsum,它将保持为 0 (FALSE),直到它遇到第一个 TRUE (1)。然后你 filter 只保留 0。

df <- data.frame(cycle = c(1:3,"***","***"),value=1:5,stringsAsFactors = FALSE) 
df%>%
  filter(cumsum(grepl("***",cycle,fixed=TRUE))<1)

  cycle value
1     1     1
2     2     2
3     3     3

我不知道 tidyverse 是否包含 正确的函数 ,但是基础 R 可以处理它(因此它可以包含在管道中).

一些示例数据:

dat <- data.frame(Cycle = c(1:5,20,"***",21,22),
                  Time  = Sys.time() + 1:9,
                  stringsAsFactors = FALSE)
dat
#   Cycle                Time
# 1     1 2017-06-26 14:02:48
# 2     2 2017-06-26 14:02:49
# 3     3 2017-06-26 14:02:50
# 4     4 2017-06-26 14:02:51
# 5     5 2017-06-26 14:02:52
# 6    20 2017-06-26 14:02:53
# 7   *** 2017-06-26 14:02:54
# 8    21 2017-06-26 14:02:55
# 9    22 2017-06-26 14:02:56


dat[! cumany(grepl("\*\*\*", dat$Cycle)),]
#   Cycle                Time
# 1     1 2017-06-26 14:02:48
# 2     2 2017-06-26 14:02:49
# 3     3 2017-06-26 14:02:50
# 4     4 2017-06-26 14:02:51
# 5     5 2017-06-26 14:02:52
# 6    20 2017-06-26 14:02:53

您可以使用

使其看起来更具可读性
dat[! cumany(grepl("***", dat$Cycle, fixed = TRUE)),]

所以它可以很容易地插入到 %>% 管道中:

library(dplyr)
dat %>%
  filter(! cumany(grepl("***", Cycle, fixed = TRUE)))

根据您显示的数据,这应该足够了。如果 $Cycle 中的值有任何歧义,您可能应该使用更有弹性的模式来匹配截止值。