[R] [Q] Setting elements of a vector

Uwe Ligges ligges at statistik.uni-dortmund.de
Mon Nov 12 22:17:20 CET 2001

Stefan Meyer wrote:
> Hi!
> I'm new to R and have problems with the following code:
> <code>
> awprob<-c(0.4,0.4,0.1,0.1)
> awsample<-sample(c(1:4),3,awprob,replace=TRUE)
> vec<-vector(mode="numeric",10000)
> vec[]<-sum(sample(c(1:4),20,awprob,replace=TRUE))
> </code>
> My problem: The elements of vec have the same value. How
> can I tell R that I want to have a *new* sample for each value
> and not 10000 times the same sample?

I don't really understand what you are going to do, but vectorizing the
last statement correctly should result in something like:

 awprob <- c(0.4, 0.4, 0.1, 0.1)
  # Matrix with 20 * 10000 samples (20 columns, 1000 rows):
 X <- matrix(sample(c(1:4), 200000, awprob, replace=TRUE), ncol=20)
  # Now applying for each row the sum():
 vec <- apply(X, 1, sum)

> A for-loop is not a good solution as it made R hang up ...

No, it won't hang up! But for such a data set a for loop is very slow.
Just wait a few minutes - or don't use for()!

Uwe Ligges
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