rwrite.table

How to write R output with unequal length into excel


I have this R code to simulate time series data, the series have 5 colomns and 35 sub

N <- c(15L, 20L, 30L, 50L, 100L)
SD = c(1, 2, 3, 4, 5) ^ 2
theta = c(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)

res <- vector('list', length(N))
names(res) <- paste('N', N, sep = '_')

set.seed(123L)
for (i in seq_along(N)){
  res[[i]] <- vector('list', length(SD))
  names(res[[i]]) <- paste('SD', SD, sep = '_')

  ma <- matrix(NA_real_, nrow = N[i], ncol = length(theta)) 

  for (j in seq_along(SD)){
    wn <- rnorm(N[i], mean = 0, sd = SD[j])
    ma[1:2, ] <- wn[1:2]

    for (k in 3:N[i]){
      ma[k, ] <- wn[k - 1L] * theta + wn[k]
    }
    colnames(ma) <- paste('ma_theta', theta, sep = '_')
    res[[i]][[j]] <- ma
  }
}

res

** I EXPECT THIS**

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

I want to write res into any of the excel file. It could be .csv file. I want 1 in one cell, 2 in one cell etc and not 12345 put together in a cell.

After then I write it to an excel file


Solution

  • The res is a nested list of matrices, we can rbind it after looping over the list

    res1 <- do.call(rbind, lapply(res, function(x) do.call(rbind, x))) 
    str(res1)
    # num [1:1075, 1:7] -0.56 -0.23 1.513 0.382 0.143 ...
    # - attr(*, "dimnames")=List of 2
    #  ..$ : NULL
    #  ..$ : chr [1:7] "ma_theta_0.2" "ma_theta_0.4" "ma_theta_0.6" "ma_theta_0.8" ...
    

    Then, the write.table works as it is a single matrix


    If we need to cbind the inner list elements, as the number of rows are different, an option is cbind.fill from rowr

    library(rowr)
    out2 <- do.call(rbind, lapply(res, function(x) 
          do.call(cbind.fill, c(as.data.frame(x), fill = NA))))
    colnames(out2) <-  make.unique(rep(colnames(res[[1]][[1]]), length.out = ncol(out2)))
    

    Update

    If we need multiple data.frame output, cbind the list elements

    res1 <- lapply(res, function(dat) do.call(cbind,  dat))
    sapply(names(res1), function(nm) write.csv(res1[[nm]], 
          file = paste0(nm, ".csv"), row.names = FALSE, quote = FALSE))