写入数据框然后写入 R 中的 .csv 文件

Write to Data Frame Then to .csv file in R

我想将下面 R 代码的输出写入 .csv 文件。

N <- c(15L, 20L)
SD <- c(1, 2) ^ 2
phi = c(0.2, 0.4)

## generate all combos
all_combos <- expand.grid(N = N, SD = SD, phi = phi)

## create function
fx_arima <- function(n, SD, phi) {
  (arima.sim(n = n,
            model=list(ar=phi, order = c(1, 1, 0)),
            start.innov = 4.1,
            n.start = 1,
            rand.gen = function(n) rnorm(n, mean = 0, sd = SD)))[-1]
}

## find arima for all combos using Map
Map(fx_arima, all_combos[["N"]], all_combos[["SD"]], all_combos[["phi"]])

## or :
set.seed(123L)
by(all_combos, all_combos["N"], 
   function(DF) {
     res = mapply(fx_arima, DF[["N"]], DF[["SD"]], DF[["phi"]])
     colnames(res) = paste("SD", DF[["SD"]], "phi", DF[["phi"]], sep = "_")
     res
   })

上面的 R 代码用不同的 N <- c(15L, 20L), SD <- c(1, 2) ^ 2, phi = c(0.2, 0.4) 值模拟 ARIMA(1,1,0)。 N=15 打印在一个矩阵中, N=20 打印在另一个矩阵中,所有列都带有列名。我希望每个矩阵都写入 datafram,然后写入将存储在我的工作目录中的 .csv 文件。

我期待这个

v1  v2   v3  v4 
1   4    3    1
2   6    3    2
3   8    3    12
4   4    4    8
5   6    4    4
6   8    4    0
7   4    5    2
8   6    5    1
9   8    5    2
10  11   12   13
11  12   13   14
8   6    5    1
9   8    5    2
10  11   12   13
11  12   13   14

我尝试了How to write R output with unequal length into excel 但无法获取

我们可以先将结果保存到列表中,final.result

final.result <- by(all_combos, all_combos["N"], 
   function(DF) {
     res = mapply(fx_arima, DF[["N"]], DF[["SD"]], DF[["phi"]])
     colnames(res) = paste("SD", DF[["SD"]], "phi", DF[["phi"]], sep = "_")
     res
   })

因为 N 组在对象的名称中而不是在列名中,我们可以使用循环将 N 附加到列名的开头 paste0。然后我们可以用write.table写出来。

for(i in seq_along(final.result)){
  group <- names(finalresult)[i]
  colnames(final.result[[i]]) <- paste0("N_",group,"_",colnames(final.result[[i]]))
  write.table(final.result[[i]],sep=",",file="test.csv",append = TRUE)
}