Nikolay Petrov
Nikolay Petrov

Reputation: 198

R: dynamic column name in for loop with cbind at each step

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:

Upvotes: 1

Views: 819

Answers (1)

dcarlson
dcarlson

Reputation: 11076

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

Upvotes: 1

Related Questions