Re: [R] How do you test for "consecutivity"?

From: Julian Burgos <jmburgos_at_u.washington.edu>
Date: Tue, 29 Apr 2008 10:07:19 -0700

Hey Anthony,
There must be many ways to do this. This is one of them:

#First, define a function to calculate the proportion of consecutive numbers in a vector.

prop.diff=function(x){
d=diff(sort(x))
prop=(sum(d==1)+1)/length(x)
return(prop)}

#Note that I am counting both numbers in a consecutive pair. For example, the vector c(1,2,6,9,10) will contain 4 consecutive numbers. I think this is what you wanted do do, right?

#Next, generate a matrix with 1000 columns (one for each experiment) and 5 rows (the five numbers in each experiment). Note the use of the 'replicate' function to generate multiple sets of random numbers

selection=replicate(1000,sort(sample(1:30,5)))

#Third, use the apply function to apply the function we defined above to each column of the matrix

diffs=apply(selection,2,prop.diff)

# This will give you a vector with the 1000 proportions of consecutive numbers

Julian

Anthony28 wrote:
> I need to use R to model a large number of experiments (say, 1000). Each
> experiment involves the random selection of 5 numbers (without replacement)
> from a pool of numbers ranging between 1 and 30.
>
> What I need to know is what *proportion* of those experiments contains two
> or more numbers that are consecutive. So, for instance, an experiment that
> yielded the numbers 2, 28, 31, 4, 27 would be considered a "consecutive =
> true" experiment since 28 and 27 are two consecutive numbers, even though
> they are not side-by-side.
>
> I am quite new to R, so really am puzzled as to how to go about this. I've
> tried sorting each experiment, and then subtracting adjacent pairs of
> numbers to see if the difference is plus or minus 1. I'm also unsure about
> whether to use an array to store all the data first.
>
> Any assistance would be much appreciated.



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. Received on Tue 29 Apr 2008 - 18:12:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Apr 2008 - 20:30:44 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive