# [R] Calculating First Occurance by a factor

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Mon Mar 30 21:37:41 CEST 2009

```one way is:

ind <- ave(Data\$IA, Data\$Sub, Data\$Tr, FUN = function (x) !duplicated(x))
Data[as.logical(ind), ]

I hope it helps.

Best,
Dimitris

jwg20 wrote:
> I'm having difficulty finding a solution to my problem that without using a
> for loop. For the amount of data I (will) have, the for loop will probably
> be too slow. I tried searching around before posting and couldn't find
> anything, hopefully it's not embarrassingly easy.
>
> Consider the data.frame, Data,  below
>
> Data
> Sub Tr  IA   FixInx  FixTime
> p1   t1  1    1        200
> p1   t1  2    2        350
> p1   t1  2    3        500
> p1   t1  3    4        600
> p1   t1  3    5        700
> p1   t1  4    6        850
> p1   t1  3    7        1200
> p1   t1  5    8        1350
> p1   t1  5    9        1500
>
> What I'm trying to do is for each unique IA get the first occurring FixTime.
> This will eventually need to be done by each Trial (Tr) and each Subject
> Number (Sub). FixInx is essentially the number of rows in a trial. The
> resulting data.frame is below.
>
> Sub Tr  IA  FirstFixTime
> p1   t1  1   200
> p1   t1  2   350
> p1   t1  3   600
> p1   t1  4   850
> p1   t1  5   1350
>
> Here is the solution I have now.
>
> agg = aggregate(data\$FixInx, list(data\$Sub, data\$Tr, data\$IA), min) #get the
> minimum fix index by Sub, Tr, and IA... I can use this min fix index to pull
> out the desired fixtime
>
> agg\$firstfixtime = 0 # new column for results
>
> for (rown in 1:length(rownames(agg))){ #cycle through rows and get each
> data\$firstfixtime from FixTime in matching rows
>   agg\$firstfixtime[rown] = as.character(data[data\$Tr == agg\$Group.2[rown] &
> data\$Sub == agg\$Group.1[rown] & data\$IA == agg\$Group.3[rown] & data\$FixInx
> == agg\$x[rown], ]\$FixTime)
> }

--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014

```

More information about the R-help mailing list