I have a large data base looking like this:
>tms
expId id date sessionNr waveSh ipi isi perc ampl qual eventNr
1 b80M1 myrthe 20131206 1 2 20 1 80 416.10 1 145
2 b80M1 myrthe 20131206 1 2 4 2 80 366.80 1 146
3 b80M1 myrthe 20131206 1 2 4 3 80 411.60 1 147
..... ...... ........ . . . . .. ...... . ...
..... ...... ........ . . . . .. ...... . ...
24 m80M1 myrthe 20131218 1 1 20 2 80 58.10 1 266
25 m80M1 myrthe 20131218 1 1 4 1 80 22.60 0 267
26 m80M1 myrthe 20131218 1 1 4 3 80 21.90 0 268
..... ...... ........ . . . . .. ...... . ...
..... ...... ........ . . . . .. ...... . ...
201 h80M1 myrthe 20131219 1 3 5 3 80 33.00 0 194
202 h80M1 myrthe 20131219 1 3 6 1 80 52.50 1 195
203 h80M1 myrthe 20131219 1 3 4 4 80 314.20 1 196
Within every tms$expId I would like to create a new variable called tms$norm. This variable represents the ratio between the tms$ampl and the mean of tms$isi==1 within an tms$expId which is tms$ampl/mean(tms[tms$isi==1,]$ampl).
I could take the long run like this, manually subsetting for every tms$expId:
b80L1 <- tms[tms$expId==b80L1,]
attach(b80L1)
b80L1$norm <- b80L1$ampl/mean(b80L1[b80L1$isi==1,]$ampl)
detach(b80l1)
m80M1 <- tms[tms$expId==m80M1,]
attach(m80M1)
M80M1$norm <- M80M1$ampl/mean(m80M1[m80M1$isi==1,]$ampl)
detach(m80M1)
h80M1 <- h80M1[h80M1$expId==h80M1,]
attach(h80M1)
h80M1$norm <- h80M1$ampl/mean(h80M1[h80M1$isi==1,]$ampl)
detach(h80M1)
And then combine all subsets again in one data frame like this:
tmsNorm <- rbind(b80L1,m80M1,h80M1)
Then the tmsNorm database would look like this:
>tmsNorm
expId id date sessionNr waveSh ipi isi perc ampl qual eventNr norm
1 b80M1 myrthe 20131206 1 2 20 1 80 416.10 1 145 0.6547
2 b80M1 myrthe 20131206 1 2 4 2 80 366.80 1 146 0.5667
3 b80M1 myrthe 20131206 1 2 4 3 80 411.60 1 147 0.6530
..... ...... ........ . . . . .. ...... . ... ...
..... ...... ........ . . . . .. ...... . ... ...
24 m80M1 myrthe 20131218 1 1 20 2 80 58.10 1 266 0.0123
25 m80M1 myrthe 20131218 1 1 4 1 80 22.60 0 267 0.0056
26 m80M1 myrthe 20131218 1 1 4 3 80 21.90 0 268 0.0057
..... ...... ........ . . . . .. ...... . ... ...
..... ...... ........ . . . . .. ...... . ... ...
201 h80M1 myrthe 20131219 1 3 5 3 80 33.00 0 194 0.0045
202 h80M1 myrthe 20131219 1 3 6 1 80 52.50 1 195 0.0053
203 h80M1 myrthe 20131219 1 3 4 4 80 314.20 1 196 0.0145
However, as I have approximately 100 types of tmse$expId, I would really like to create this tms$norm variable using a loop function or some kind of apply function.
I tried using this code which does not work but hopefully indicates what I'm trying to achieve:
uniq <- unique(unlist(tms$expId))
> for(i in 1:length(uniq)){
attach(tms[tms$expId==uniq[i], ])
tms$normReal2 <- tms[tms$expId==uniq[i], ]$realAmpl/mean(tms[(tms$expId==uniq[i]) | (tms$isi==1),]$realAmpl)
detach(tms[tms$expId==uniq[i], ])
}
So my question is: how do I achieve to create this tms$norm variable using a very compact code?
Thank yo very much in advance!