[R] avoiding the sample in built function

David Winsemius dwinsemius at comcast.net
Wed Nov 23 21:24:57 CET 2011


On Nov 23, 2011, at 2:56 PM, Kevin E. Thorpe wrote:

> On 11/23/2011 02:01 PM, sarah44 wrote:
>> Dear all,
>>
>> I am currently working on a function in which I would like to avoid  
>> using
>> the command sample().
>>
>> Therefore, I am now trying to make a for loop that does the same  
>> thing as
>> the in built function sample
>> does: Rearranging the items of a object randomly.
>>
>> So, the output I want to you get is the same as sample() would give  
>> me:
>>
>> e.g.:
>> data<- c(5,4,6,7,8)
>> sample(data)
>>
>>> data<- c(5,4,6,7,8)
>>> sample(data)
>> [1] 4 6 7 8 5
>>> sample(data)
>> [1] 6 8 4 7 5
>>> sample(data)
>> [1] 6 5 4 8 7
>>
>> Herefore I made a for loop which you can see here:
>> This for loop is supposed to do the same as the sample() function,  
>> 3 times.
>>
>> data<- c(5,4,6,7,8)
>> numsim<- 3
>> n<- length(data)
>> sample<- matrix(0,numsim,1)
>>
>>
>> for (i in 1:numsim) {indices<- runif(pool, min = 1, max = n)
>>                   sample[i,]<- data[indices]
>>                       }
>>
>> the idea behind this for loop is dat it first creates randomly data  
>> by
>> runif, and then it should
>> somehow, by using indeces, store this 3 times in a matrix 'sample'.
>> Somehow, I am stuck here and I think that the sample[,i] part is  
>> just very
>> wrong. I am however
>> not for a very long time an R user, so I cannot find the solution  
>> to this
>> problem.
>>
>> Can someone give me a hint?
>>
>> Thanks very much!
>>
>> Bye, sarah
>>
>
> The only reason I can think of you wanting to avoid sample() is  
> because this is homework and the list is not for homework.  If I  
> have misjudged the intent of your post, please forgive me.

Furthermore a similar question was already asked and answered on the  
list recently, so it appears to be a common programming exercise. (My  
response to that one was to offer a hint but the questioner didn't  
quite get it so it took a couple of days for the answer to apper.)  
Perhaps the real test is to see if one knows how to search?

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list