Daniel James
Daniel James

Reputation: 1433

Write to Data Frame Then to .csv file in R

I want the output of the bellow R code be written to .csv file.

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

The above R code simulate ARIMA(1,1,0) with varying values of N <- c(15L, 20L), SD <- c(1, 2) ^ 2, phi = c(0.2, 0.4). N=15 is printed in a matrix and N=20 is printed in another matrix all columns with column name. I want each matrix be writen in datafram and then written to .csv file that will be stored in my working directory.

I EXPECT THIS

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

I tried what was done in How to write R output with unequal length into excel but couldn't get it

Upvotes: 2

Views: 232

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

We could first, save the results to a list, 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
   })

Because the N group is in the name of the object and not in the column names, we can use a loop to append the N to the begining of the column names with paste0. Then we can write out with 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)
}

Upvotes: 1

Related Questions