0

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?

rm167
  • 1,185
  • 2
  • 10
  • 26
  • 1
    have you tested `dplyr` for this problem? So there it would be basically `group_by(a,b) and pipe it to `summarise` and execute your function. – drmariod Mar 14 '17 at 12:19
  • Yes, `dplyr`s`group_by(a,b) %>% mutate/summarize(...)` is exactly what you want – smci Mar 14 '17 at 12:22
  • Could you please show an example of the result you would like to get? – RRuiz Mar 14 '17 at 12:25
  • You may try: `library(data.table); setDT(df)[, your_function(t), by=.(a, b)] ` – Uwe Mar 14 '17 at 12:30
  • @bouncyball I don't think I can use aggregate as the function i want to use is more complicated. – rm167 Mar 14 '17 at 13:07
  • @RobertoRuiz I have added some more details. I hope it is clear now? – rm167 Mar 14 '17 at 13:07
  • Not really. My English is not enough good. I need to see the numbers you want to obtain. I think I have made something similar before.. So (from your example), the result of the row 101 would be 1 and of the row 102 would be 60, and for the 103, 61 ? – RRuiz Mar 14 '17 at 19:35

0 Answers0