# [R] How to use apply() to fill matrix by rows or columns?

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sat Feb 25 02:50:05 CET 2017

```The apply function is one of many alienate ways to write a loop. It is not appreciably more efficient in cpu time than a for loop.

Your example creates the numbers in the loop... does your actual data get created in a loop? If so then your original code should be perfectly serviceable. If not then there might be a better way to do this, but you would have to expand your example to illustrate how the data comes to you in order to suggest alternatives.

Also post using plain text to prevent your code from being mangled on its way to us.
--
Sent from my phone. Please excuse my brevity.

On February 24, 2017 5:27:07 PM PST, C W <tmrsg11 at gmail.com> wrote:
>In theory, I am generating from group 5 groups of random numbers, each
>group has 3 samples.
>
>Isn't apply() the replacement of loops?
>
>On Fri, Feb 24, 2017 at 8:23 PM, Jeff Newmiller
><jdnewmil at dcn.davis.ca.us>
>wrote:
>
>> What is wrong with
>>
>> dat <- matrix(rnorm(15), nrow=5, ncol = 3)
>>
>> ?
>>
>> And what is this "no loop drama" you refer to? I use loops frequently
>to
>> loop around large memory gobbling chunks of code.
>>
>> --
>> Sent from my phone. Please excuse my brevity.
>>
>> On February 24, 2017 5:02:46 PM PST, C W <tmrsg11 at gmail.com> wrote:
>> >Dear R,
>> >
>> >I wanted to simulate a 5 by 3 matrix which fills up by either rows
>or
>> >columns?
>> >
>> >I started with the following filling the matrix by rows,
>> >
>> >dat <- matrix(NA, nrow=5, ncol = 3)
>> >
>> >for(i in 1:5){
>> >
>> >    dat[i, ] <- rnorm(3)
>> >
>> >}
>> >
>> >But, R is known for no loop drama. Any suggestions?
>> >
>> >Thanks!
>> >
>> >       [[alternative HTML version deleted]]
>> >
>> >______________________________________________
>> >R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> >https://stat.ethz.ch/mailman/listinfo/r-help