R:for循环中的动态列名称,每一步都有cbind

时间:2015-12-09 19:10:11

标签: r cbind

我的代码是:

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]
}

其中

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

我想在第一个循环中得到这个:

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

与此相反:

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

分别为第二个循环:

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

与此相反:

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

我发现了this类似的问题,但我找不到解决方案:

1 个答案:

答案 0 :(得分:1)

您是否决定使用for循环?

> 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