# [R] Random Relabelling

Peter Ehlers ehlers at ucalgary.ca
Sat Apr 23 15:15:23 CEST 2011

```On 2011-04-23 03:42, John Kane wrote:
> I KNEW there was a better way!
>
> --- On Wed, 4/20/11, Jeremy Hetzel<jthetzel at gmail.com>  wrote:
>
>> From: Jeremy Hetzel<jthetzel at gmail.com>
>> Subject: Re: [R] Random Relabelling
>> Cc: r-help at r-project.org, "Kevin Matthews"<kevin-matthews at uiowa.edu>
>> Received: Wednesday, April 20, 2011, 2:25 PM
>> Kevin,
>>
>> The following follows John's suggestion, but without the
>> loop.  It's quick
>> for me.
>>
>> Jeremy
>>
>>
>> Jeremy T. Hetzel
>> Boston University
>>
>>
>>
>> ## Generate sample data
>> n<- 4000
>> rep<- 1000
>> rate<- rnorm(n, mean = 15, sd = 2) / 100000 # Mortality
>> rates around
>> 15/100k
>>
>> ## Create an empty matrix with appropriate dimensions
>> permutations<- matrix(ncol = n, nrow = rep)
>>
>> ## Use apply() to resample
>> permutations<- apply(permutations, 1, function(x)
>> {
>> sample(rate, size = n, replace = F)
>> })
>>
>> ## Look at the matrix
>> dim(permutations)
>>
>> ## Find the column means
>> means<- apply(permutations, 1, mean)
>> means
>>

And you might note that

means <- rowMeansy(permutations)

is about 10-15 times faster (if speed matters).

Peter Ehlers

[...snipped...]

```