[R] Please help with loop, thanks
Marc Schwartz
marc_schwartz at me.com
Thu Mar 18 21:00:31 CET 2010
Mark,
Sorry to come to the party late, but if the result vectors are going to be the same length:
mat <- matrix(rnorm(40), 10, 4)
colnames(mat) <- c("A","B","C","D")
> mat
A B C D
[1,] -0.6489907 -1.000256771 0.69287228 0.81174708
[2,] 0.1899992 -0.002432263 0.25729895 -1.75892514
[3,] -0.8876303 0.918710108 -0.36694127 0.31080813
[4,] 0.7344414 -1.619137824 0.46113302 -1.12355377
[5,] 0.6041401 -1.214494484 0.09514796 -0.40251412
[6,] -1.2832537 0.478327783 -0.27581631 0.38287704
[7,] -0.2187174 0.656607367 -1.34435465 -0.03977851
[8,] 0.7219878 -0.812492310 -0.37206013 -0.57919470
[9,] 1.2644850 0.451997047 0.53445595 0.46368201
[10,] 0.2768631 0.756866311 1.27080049 0.74773388
If they are not:
individuals <- list(A = 5, B = 3, C = 7 , D = 10)
> lapply(individuals, rnorm)
$A
[1] 0.2985010 -1.6668673 -0.5972911 -0.4900159 -0.8235880
$B
[1] 0.3108316 -0.5031473 -0.7155617
$C
[1] -0.2670414 1.9196313 -2.0528845 -1.3008695 -0.6812742 -0.1673367
[7] 1.5839630
$D
[1] -0.4027003 -0.4710862 -0.8342229 0.4622410 1.4038563 1.1073825
[7] -0.2315623 -0.4758547 1.8888324 -0.4614643
HTH,
Marc Schwartz
On Mar 18, 2010, at 2:35 PM, Mark Na wrote:
> Many thanks to everyone who helped me solve this problem.
>
> I think I must have described my problem poorly, but Phil, Patrick and Jim
> were able to see through the haze and suggest that I use a list to contain
> the output from my loop. This solution works very well.
>
> Thanks again for your help, Mark
>
>
>
>
> On Thu, Mar 18, 2010 at 12:44 PM, Mark Na <mtb954 at gmail.com> wrote:
>
>> Dear R helpers,
>>
>> I would like to write a loop that makes 4 objects (called A, B, C, and D)
>> each of which contains ten random numbers.
>>
>> This attempt:
>>
>> individuals<-c("A","B","C","D")
>> for(i in 1:length(individuals)) {
>> individuals[i]<-rnorm(10)
>> }
>>
>>
>> does not work because "individuals[i]" is not the proper way to extract
>> each letter from the object called "individuals" (rather, it tries to assign
>> the random numbers to various positions within "individual")
>>
>> So, my question is, what should be to the left of the gets operator in the
>> third line?
>>
>> Many thanks,
>>
>> Mark Na
>>
>
>
>
> --
> Mark Na
> University of Saskatchewan
> Saskatoon, Canada
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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