1

My code is:

N = 4;

pred_sales_mean <- c(Q1 = 11000, Q2 = 15000, Q3 = 16000, Q4 = 11000)
pred_sales_sd <- c(Q1 = 3000, Q2 = 4000, Q3 = 5000, Q4 = 3000)

pred_sales <- rbind(mean = pred_sales_mean, sd = pred_sales_sd)

sales <- vector()
for (q in paste("Q", 1:4, sep = "")){
            sales <- cbind(sales, q = round(rnorm(N, pred_sales['mean',q], pred_sales['sd',q])));
    # other code indexing sales[,q]
}

where

> pred_sales
        Q1    Q2    Q3    Q4
mean 11000 15000 16000 11000
sd    3000  4000  5000  3000

I would like to get this in the first loop:

> sales
      Q1
 [1,]  8
 [2,]  1
 [3,] -7
 [4,] -4

as opposed to this:

> sales
      q
[1,]  8
[2,]  1
[3,] -7
[4,] -4

respectively for the second loop:

> sales
      Q1 Q2
 [1,]  8 -3
 [2,]  1  4
 [3,] -7  0
 [4,] -4 -1

as opposed to this:

> sales
      q  q
[1,]  8 -3
[2,]  1  4
[3,] -7  0
[4,] -4 -1

I found this simular question, but the solution I am looking for is not given there:

Community
  • 1
  • 1
Nikolay Petrov
  • 188
  • 2
  • 6
  • Just do `names(sales) <- paste0("Q", 1:4)` after the loop is over? Though the whole concept of growing objects in a for loop is fundamentally incorrect when it comes to R at least. It's better you will explain what you actually trying to achieve and we will try to guide in the better direction. For instance, you loop could be converted to just `sales <- matrix(round(rnorm(16, 1, 5)), 4) ; colnames(sales) <- paste0("Q", 1:4)`. – David Arenburg Dec 09 '15 at 19:18
  • I edited the post with some clarificaiton about what I am after. – Nikolay Petrov Dec 09 '15 at 19:53
  • So can't you just do `matrix(rnorm(16, unlist(pred_sales[1, ]), unlist(pred_sales[2, ])), 4)`? (in case `pred_sales` is a `data.frame`. You don't need `unlist` if its a `matrix`) – David Arenburg Dec 09 '15 at 19:59
  • This seems to work. Thanks. – Nikolay Petrov Dec 09 '15 at 20:25
  • But you need to transpose the result since Q1 is the first row, not the first column since the matrix is filled by column cycling through the 4 values for mean and sd unless you add byrow=TRUE. – dcarlson Dec 10 '15 at 21:17

1 Answers1

1

Are you determined to use a for loop?

> result <- sapply(1:N, function(x) round(rnorm(4, 
+      pred_sales["mean", x], pred_sales["sd", x])))
> colnames(result) <- paste0("Q", 1:4)
> result
        Q1    Q2    Q3   Q4
[1,] 13209 17186 16570 8510
[2,] 15586  9408 16366 7209
[3,] 10443 19492 10887 9231
[4,] 13215 11634 20564 8990
dcarlson
  • 10,936
  • 2
  • 15
  • 18