【问题标题】:Logical operation on data frame of column 2 returning corresponding column 1 value对第 2 列数据框的逻辑运算返回对应的第 1 列值
【发布时间】:2014-07-23 21:48:28
【问题描述】:

我有一个如下所述的数据框,我想对该列进行一些逻辑分析 命名为“a”。对于每个 ID,我都有“a”的起始值 (@t=o),称为基线。 我正在输入“a”数据并检查我的 a>=baseline.If TRUE 然后继续。 如果为 FALSE,则记下相应的 t 值(当您观察到第一个 FALSE 时)。 像这样,如果你没有找到 TRUE 然后记下 t 的最后一个对应值... 为了更好地理解,我给出了以下示例。 你能建议我一些合适的方法吗?我不想使用 FOR 循环。

ID  t  a    To understand column
 1   0  12   TRUE  (this a value is baseline for ID=1)
 1   5  16   TRUE  (a>=baseline)
 1   10 18   TRUE   ...so on..
 1   15 20   TRUE (upto here we found all TRUE so take this last corresponding t value)
 2   0  16   TRUE   (this a value is baseline for ID=2)
 2   2  19   TRUE 
 2   4   9   FALSE  (here a>=16 is not satisfied)So take that corresponding t value
 2   6  25   TRUE 
 3   0  50   TRUE 
 3   3  52   TRUE 
 3   6  55   TRUE 
 3   8  49   FALSE (here a>=50 is not satisfied)so take that corresponding value


 ID=c(1,1,1,1,2,2,2,2,3,3,3,3)
 t=c(0,5,10,15,0,2,4,6,0,3,6,8)
 a=c(12,16,18,20,16,19,9,25,50,52,55,49)
 data= data.frame(ID,t,a)


#Desired Output (by using Stack/split by ID or **some other possible ways**..)
ID   t
1  15 (#We didn't find FALSE so took the last t element of that ID )
2   4 (#wherever we find first FALSE take the corresponding value of t at that ID)
3   8 (#same like ID=2 but to explain the example it happened at last t element of that ID)

【问题讨论】:

  • 您能否发布一些示例数据以供使用以及您尝试过的内容
  • @rawr 你能看一下吗?

标签: r if-statement dataframe


【解决方案1】:

我仍然是 R 的初学者,但这里有一个相当简单的版本,肯定可以清理;

> do.call("rbind", lapply(split(data, ID), 
    function(x) {
        z = x['a']>=cummax(x['a']); z[length(z)]=FALSE; head(x[!z,],1)
    }
))

  ID  t  a
1  1 15 20
2  2  4  9
3  3  8 49

它的作用基本上是按 ID 拆分帧,并为每个生成的帧找到序列中第一个递减值的行(如果不匹配则回退到最后一个)并重新合并帧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2020-06-09
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多