# [R] Loop removal?

rijn@swi.psy.uva.nl rijn at swi.psy.uva.nl
Mon Jul 31 16:30:53 CEST 2000

```Peter,

> >   bin.index <- function(data,bins=2) {
> >     # Code from Peter Malewski, added the sort command.
> >     sort(rep(rep(1:bins,rep(length(data)/bins,bins)),length.out=length(data)))
> >   }
>
> with your outside-sort you have avoided a hidden bug in my example:

Well, as R-beginner I didn't know whether it was a bug or a feature, but
adding the sort solved it for the bin=2 tests I did. I also discovered the
problem (about half an hour ago with the real data) you mentioned in your
ps:

> ps.: what happens when there is more than 1 resting element?
> > 8 %% 3
> [1] 2
> > x<- 1:8 ;cbind(x,xx(x ,3))
>      x
> [1,] 1 1
> [2,] 2 1
> [3,] 3 1
> [4,] 4 1
> [5,] 5 2
> [6,] 6 2
> [7,] 7 3
> [8,] 8 3
>
> ???

I solved it (hacked around it?) using the following code:

bin.index <- function(data,bins=2) {
bin.index <- rep(1:bins,rep(length(data)/bins,bins))
if (length(data) %% bins) {
bin.index <- c(bin.index,1:(length(data) %% bins))
}
sort(bin.index)
}

> bin.index(1:9,bins=5)
[1] 1 1 2 2 3 3 4 4 5

(I've also considered using:

sort(rep(
c(rep(1:bins,rep(length(data)/bins,bins)),1:bins),
length.out=length(data)))

but that statement is probably to complicated for me to understand easily in
a couple of days... But would this second method be the preferred way
in R?)

And regarding the issue of deciding to which group the remaining items
belongs, I've just decided to add them to the first groups. The number of
observations in each group is quite high as is the number of subjects, so I
don't expect any real problems. However, if the rebinned data should show
different results than the original data, I'll make sure to have an equal
number of cases in cell.

Thanks for all your kind help,
Hedderik.

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```