[R] Apply a shift which is a function of the array.

Robin Hankin rksh1 at cam.ac.uk
Fri Jul 2 13:22:01 CEST 2010


Hello again Jim

It seems that ashift() from the same package *doesn't* do what you want.

But you can use shift() as follows:

 > myshift <- function(x){shift(x,1-which.max(x))}
 > a <- matrix(runif(30),5,6)

 > a
             [,1]       [,2]      [,3]       [,4]       [,5]      [,6]
[1,] 0.268955362 0.18446939 0.6489957 0.51000680 0.05877378 0.6671306
[2,] 0.007827401 0.03128131 0.7508847 0.27802680 0.93626913 0.2460778
[3,] 0.936496465 0.96065059 0.5452295 0.04976117 0.91768925 0.3285821
[4,] 0.244059311 0.31785472 0.7398967 0.31343310 0.67126086 0.2168343
[5,] 0.083498454 0.24745674 0.3611509 0.74341994 0.45215530 0.7454390
 > t(apply(a,1,myshift))
           [,1]       [,2]        [,3]       [,4]      [,5]       [,6]
[1,] 0.6671306 0.26895536 0.184469391 0.64899567 0.5100068 0.05877378
[2,] 0.9362691 0.24607779 0.007827401 0.03128131 0.7508847 0.27802680
[3,] 0.9606506 0.54522946 0.049761166 0.91768925 0.3285821 0.93649646
[4,] 0.7398967 0.31343310 0.671260864 0.21683431 0.2440593 0.31785472
[5,] 0.7454390 0.08349845 0.247456736 0.36115095 0.7434199 0.45215530
 > apply(a,2,myshift)
             [,1]       [,2]      [,3]       [,4]       [,5]      [,6]
[1,] 0.936496465 0.96065059 0.7508847 0.74341994 0.93626913 0.7454390
[2,] 0.244059311 0.31785472 0.5452295 0.51000680 0.91768925 0.6671306
[3,] 0.083498454 0.24745674 0.7398967 0.27802680 0.67126086 0.2460778
[4,] 0.268955362 0.18446939 0.3611509 0.04976117 0.45215530 0.3285821
[5,] 0.007827401 0.03128131 0.6489957 0.31343310 0.05877378 0.2168343
 >




rksh



On 07/02/2010 12:05 PM, Jim Hargreaves wrote:
> Dear List,
>
> I have a 2,000x10,000 array of time domain data which when plotted 
> draws a distinct pulse. The matrix is 10,000 pulses of length 2000. I 
> would like the pulse to be shifted so that the peak (which.max of the 
> pulse data) is consistently at point 400.
>
> I don't want to use loops as it'll take a long time. The problem with 
> using apply is the pulse peak varies for each pulse, so I want to use 
> something like:
>
> apply(really_mean_pulse, 2, shift, which.max(really_mean_pulse))
>
> (Using the shift function from the "magic" library)
>
> This doesn't work, so I need to modify this so that the argument to 
> shift is dependent on the column the shift is being applied to.
>
> Any suggestions would be greatly appreciated!
>
> Kind Regards,
> Jim Hargreaves
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Robin K. S. Hankin
Uncertainty Analyst
University of Cambridge
19 Silver Street
Cambridge CB3 9EP
01223-764877



More information about the R-help mailing list