# [R] Help on loops

jim holtman jholtman at gmail.com
Wed Dec 8 02:47:19 CET 2010

```use split and lapply to make it easier.  Substitute in your own
calculations since this is just an example:

> x
id t X1 X2
1  1 1  4  3
2  1 2  9  2
3  1 3  7  3
4  1 4  6  6
5  2 1  6  4
6  2 2  5  3
7  2 3  1  1
8  3 1  9  6
9  3 2  5  5
> # first split the data by 'id'
> x.s <- split(x, x\$id)
> # then process each group
> result <- lapply(x.s, function(.grp){
+     output <- .grp[1, 3:4] * 4  # data from the first row
+     i <- 2
+     # repeat for the rest of the row
+     while (i <= nrow(.grp)){
+         output <- output + .grp[i, 3:4] * 2
+         i <- i + 1
+     }
+     output  # return value
+ })
> result
\$`1`
X1 X2
1 60 34

\$`2`
X1 X2
5 36 24

\$`3`
X1 X2
8 46 34

>

On Tue, Dec 7, 2010 at 5:43 PM, Anup Nandialath
<anup_nandialath at yahoo.com> wrote:
> Dear R-helpers,
>
> I have a basic question on using loops.
>
> I have a panel data set with different variables measured for "n" firms over "t" time periods. A snapshot of the data is given below
>
> id    t    X1    X2
> 1    1     4    3
> 1    2    9    2
> 1    3    7    3
> 1    4    6    6
> 2    1    6    4
> 2    2    5    3
> 2    3    1    1
> 3    1    9    6
> 3    2    5    5
>
> thus total sample n=9
>
> My problem is as follows. I need to do some computations on the data where the first observation for each firm (ie. id=1 and t=1; id=2 and t=1; id=3 and t=1) requires a specific operation on x1 and x2 and the subsequent operations are based on the computed value of the first operation.
>
> For example the pseudocode is as follows
>
> ##define output matrix
>
> output <- rep(0,n)
>
> ## define coefficient vector
> b <- c(1,1)
>
> for (i in 1:number of simulations)
> {
>    for (j in 1:id)
>     {
>       for(k in 1:t)
>          {
>            if(Data\$t[,2]==1)
>               {
>                  meanvec <- Data[k,3:4]%*%b
>                  output[k] = calc (meanvec) # output from calc is a scalar
>               }
>             else
>                   output[k]= calc(a*output[k-1]+Data[k,3:4]%*%b)
>            }
>        }
>     }
>
> Thus the end result should be a vector "output" with nine observations based on the computations.
>
> I hope the problem is clear and I greatly appreciate any help in solving this problem . Thanks in advance for your help.
>
> Kind Regards
>
> Anup
>
>
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>
>

--
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?

```