Randomize Treatments

From MagnetoWiki
Jump to: navigation, search

A quick bit of Scheme/Racket to produce a list of randomized treatments across a group of subjects.

Usage:

(randomize-treatments #:list treatments #:forSubjectCount number-of-subjects)

given a list of treatments and an integer number of subjects, call randomize-treatments:

> (define treatments '(drug1 drug2 drug3 drug4))
> (define number-of-subjects 6)
> (randomize-treatments #:list treatments #:forSubjectCount number-of-subjects)
6	drug2	drug1	drug3	drug4
5	drug3	drug4	drug2	drug1
4	drug3	drug2	drug1	drug4
3	drug1	drug4	drug3	drug2
2	drug2	drug3	drug4	drug1
1	drug4	drug2	drug3	drug1
done
>


Here is the the source listing.

#lang racket

; randomize-treatments 
; given a list of treatments and a number of subjects, 
; prints out a list of treatments for each subject

; see usage example at bottom

(define shuffle ; Returns a randomly re-ordered copy of list.
  (lambda (list)
    (if (< (length list) 2) 
        list
        (let ((item (list-ref list (random (length list)))))
          (cons item (shuffle (remove item list)))))))

(define display-list-with-tabs; prints a list with tabs between members
  (lambda (list)
    (if (> (length list) 0)
        (begin
          (display (car list))
          (if (> (length (cdr list)) 0) 
              (display "\t") 
              #f)
          (display-list-with-tabs (cdr list)))
        (displayln "")
        )))
        
               
(define randomize-treatments 
  ; given a list of treatments and a number of subjects, 
  ; prints out a list of treatments for each subject
  (lambda (#:list rx-list #:forSubjectCount n )
    (if (> n 0)
        (begin 
          (display n)(display "\t")
          (display-list-with-tabs (shuffle rx-list))
          (randomize-treatments #:list rx-list #:forSubjectCount (sub1 n)))
        (displayln 'done)
        )))

; usage
;(define treatments '(drug1 drug2 drug3 drug4))
;(define number-of-subjects 6)
;(randomize-treatments #:list treatments #:forSubjectCount number-of-subjects)