我有一个下面描述的数据框,我想对该列进行一些逻辑分析 名为“a”。对于每个ID,我有一个名为“a”的起始值(@ t = o)。 我输入“a”数据并检查我的a> gt = = 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)
答案 0 :(得分:2)
我仍然是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
它的作用基本上是按帧分割帧,并且对于每个结果帧,找到具有序列中第一个递减值的行(如果没有匹配则回落到最后一个)并重新合并帧。