[R] Loop removal?

rijn@swi.psy.uva.nl rijn at swi.psy.uva.nl
Sun Jul 30 01:01:30 CEST 2000


Hi,

> Look at the help for the cut() function, which does what you want, 
> I think.

Thanks for the suggestion. I'm sure I can put it to good use in another
part of the analysis, but it does not exactly what I want for this problem
(as far as I understand). Given the following example:

x <- c(1,1,2,3,4,4,3,2,1,1)

And assuming I want to divide x into to equally long sets to which the
values get assigned in increasing order, cut doesn't do the job:

> cut(x,c(1,2,4),labels=F,include.lowest=T)
 [1] 1 1 1 2 2 2 2 1 1 1
> table(cut(x,c(1,2,4),labels=F,include.lowest=T))

1 2 
6 4 
> 

Whereas I'm looking for an output that results in:

> table(...(x,...))

1 2
5 5
>

So, the assignment of factors is not only based on the size of the numbers
in the vector, but also on the lengths of the resulting vectors.

And, it still leaves this "loop"-problem:

> > for (i in unique(stor$subject)) {
> >   stor[stor$subject == i,]$bin <- bindata(stor[stor$subject == i,]$rt)
> > }

I assume I should use a function like tapply, but:

> bindata2 <- function(rt) {
+   
+   bindata <- rep(-1,length(rt))
+   binwidth <- length(rt)/2
+   
+   bindata[order(rt)[(0*binwidth)+1:(1*binwidth)]] <- 1
+   bindata[order(rt)[(1*binwidth)+1:(2*binwidth)]] <- 2
+ 
+   bindata
+ }
> x <- data.frame(subject=c(1,1,1,2,2,2),rt=c(1,2,3,3,2,4))
> tapply(x$rt,x$subject,bindata2)
$"1"
[1] 1 2 2

$"2"
[1] 2 1 2

the problem is that I don't know how to combine/concatenate the output of
tapply into one vector again. So, it's probably all caused by a very
simple "lack of knowledge about R" on my side...

Right now, I use tapply, but use a for-loop again to concatenate the list
into a single vector again. But it feels like there should be a better
solution. I someone can hint me towards one, I would be very pleased.

   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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list