【问题标题】:Extract rows for first occurrence of a variable prior to the occurrence of an event在事件发生之前提取变量第一次出现的行
【发布时间】:2019-02-08 14:59:31
【问题描述】:

尝试在数据框中已选择的特定值之前提取数据框中第一次出现的变量。具体来说,head(df) 的输出为:

date discharge     event event.isolation some.column
1/1/2016  7.782711         NA  NA             FALSE
1/2/2016  7.349389  -5.567748  none            TRUE
1/3/2016  7.053813  -4.021769  none            TRUE
1/4/2016  7.421568   5.213554  none            TRUE
1/5/2016  5.722443 -22.894418  none            TRUE
1/6/2016  5.497342  -3.933662  none            TRUE
1/7/2016  5.347890  -6.898281  none            TRUE
1/8/2016  7.983489   4.289382  none            TRUE
1/9/2016  8.488293  -19.28304  none            TRUE

我想在每个event 的-22 或更低之前找到第一个discharge 值7.7 或更大的date。换句话说,我知道每个感兴趣的event;我想迭代地向后搜索以在每个选定的 event 之前找到第一个 7.7 或更大的 discharge 值。

我基本上是在尝试将Extract rows for the first occurrence of a variable in a data frame 与Select row prior to first occurrence of an event by group 结合起来,但我遇到了困难。

所需的结果将是 df[1, ],因为它包含第一个超过 7.7 的 discharge 值(向后计算),位于我选择的第 5 行中的 event 之前。

【问题讨论】:

  • 如果你展示你预期的输出答案会更容易和更好的质量
  • 1. dput(head(df)) 的发布结果 2. 像示例数据一样显示您的期望结果
  • 您的df 似乎缺少其中一列的标题。另外,你能提供几行吗?
  • @MKBakker 我又添加了几个;这有帮助吗?
  • @BrynnO'donnell 多写几行,其中 event

标签: r filter grouping


【解决方案1】:

这不是最优雅的解决方案,但它适用于示例。

这首先定义了外观的间隔(每个event < -22 一个间隔)。然后寻找discharge > 7.7的第一次出现

我假设在这个例子中你不想找到 event < -22 和 discharge > 7.7 所在的行,即使那是自上次事件以来discharge > 7.7 的第一次出现

df <- read.csv(text = 'date discharge     event event.isolation some.column
1 1/1/2016  7.782711         NA  <NA>           FALSE
 2 1/2/2016  7.349389  -5.567748  none            TRUE
 3 1/3/2016  7.053813  -4.021769  none            TRUE
 4 1/4/2016  7.421568   5.213554  none            TRUE
 5 1/5/2016  5.722443 -22.894418  none            TRUE
 6 1/6/2016  5.497342  -3.933662  none            TRUE
 7 1/7/2016  5.347890  -6.898281  none            TRUE
 8 1/8/2016  7.983489   4.289382  none            TRUE',sep="")

## look which rows have a value for event < 22 and also include row 0 to define the first interval to look
 d <- c(0,which(df$event < -22))

## Each interval is defined as d[i] to d[i+1], where intervals are skipped where these are equal (because then you would return rows where both event < -22 and discharge > 7.7
new.df <- NULL
 for(i in 1:(length(d)-1)) {
  if(d[i+1] > (d[i] + 1)) {
   ## this will look only in the interval and return the first row for which the condition discharge>7.7 is TRUE
   new.df <- subset(df[(d[i]+1):(d[i+1]-1),], discharge>7.7)[1,]
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 2013-11-25
    • 2013-12-29
    • 2020-09-02
    • 2021-09-30
    • 2018-12-21
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多