[R] Grouping Numbers

Jason Rupert jasonkrupert at yahoo.com
Thu Mar 26 04:20:47 CET 2009


Jorge, 

Thank you very much for your post. 

I tried the below with a few modifications:
# First case
N<-100000
X<-rnorm(N)
step_size<-1

# Groups
g<-rep(1:(N/step_size),each=step_size)

# The result
tmp_output<-tapply(X,g,mean)

length_tmp_output<-length(tmp_output)
tmp_x_vals<-rep(step_size,length_tmp_output)
plot(tmp_x_vals, tmp_output)

for(ii in 1:val_size)
{   
step_size<-ii

# Groups
g<-rep(1:(N/step_size),each=step_size)

# The result
tmp_output<-tapply(X,g,mean)

length_tmp_output<-length(tmp_output)
tmp_x_vals<-rep(step_size,length_tmp_output)
points(tmp_x_vals, tmp_output)
}

However, when I change the step_size to 100, I receive the following error:
"Error in tapply(X, g, mean) : arguments must have same length"

Do you have any idea why the for loop crashes?  

I figured it would run smooth since it runs fine prior to the loop. 

Thanks for any insights. 




--- On Tue, 3/24/09, Jorge Ivan Velez <jorgeivanvelez at gmail.com> wrote:

> From: Jorge Ivan Velez <jorgeivanvelez at gmail.com>
> Subject: Re: [R] Grouping Numbers
> To: jasonkrupert at yahoo.com
> Cc: R-help at r-project.org
> Date: Tuesday, March 24, 2009, 10:28 PM
> Dear Jason,
> Try this:
> 
> # First case
> N<-100000
> X<-rnorm(N)
> 
> # Groups
> g<-rep(1:(N/n),each=10)
> 
> # The result
> tapply(X,g,mean)
> 
> 
> For the second case, just change each=10 by each=100 and
> run again the code
> above.
> 
> HTH,
> 
> Jorge
> 
> 
> On Tue, Mar 24, 2009 at 10:52 PM, Jason Rupert
> <jasonkrupert at yahoo.com>wrote:
> 
> >
> > Ugh...This should be very simple, but evidently I am
> not searching for the
> > proper term.
> >
> > Given the below:
> > val_size<-100000
> > x_vals<-rnorm(val_size)
> >
> > I would like to group them according to the following
> > x_vals_mean_tmp[1]<-mean(x_vals[1:10])
> > x_vals_mean_tmp[2]<-mean(x_vals[11:20])
> > ...
> > x_vals_mean_tmp[n]<-mean(x_vals[99991:100000])
> >
> > Then,
> > I would like to group them according to the following
> > x_vals_mean_tmp[1]<-mean(x_vals[1:100])
> > x_vals_mean_tmp[2]<-mean(x_vals[101:200])
> > ...
> > x_vals_mean_tmp[m]<-mean(x_vals[99901:100000])
> > etc.
> >
> > I'm pretty sure I can come up with a loop to do
> this, but wondering if
> > there is something that will allow me to break up the
> x_vals vector
> > according to a certain step size.  I looked at split
> and cut, but those did
> > not appear to accomplish what is needed.
> >
> > Thanks again.
> >
> > ______________________________________________
> > 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.
> >




More information about the R-help mailing list