I am trying to apply a function to each and every subsets of a data frame based on values in two columns. The following example is a simplified representation of my problem.
Say I have the following data frame
a=rep(1:5,each=5,times=5)
b=rep(c(2,6,9,10,12),each=25)
t=rep(seq(0,20,5),times=25)
df=as.data.frame(cbind(a,b,t))
t
is a time step. and I want to apply a continuous function (means I can't just apply the function for each and every row before sub-setting which will make the task much easier) for each subsets based on a and b values i.e for each df[df$a==A & df$b==B,]
where A=1,..,5
and B=11,...,15
.
e.g.
df[df$a==1 & df$b==12,]
a b t
101 1 12 0
102 1 12 5
103 1 12 10
104 1 12 15
105 1 12 20
and the function I want use is dependent on all three variables (a, b and t)
(e.g. a^2+b*t-c
where c
is the result of last time step, this is why I can't just apply the function for each and every row before sub-setting).
I tried with using functions like split
/subset
and apply
. But I couldn't solve it. Can somebody help?