]> git.donarmstrong.com Git - r/common_r_code.git/commitdiff
add array to excel
authorDon Armstrong <don@donarmstrong.com>
Mon, 31 Oct 2016 22:14:56 +0000 (17:14 -0500)
committerDon Armstrong <don@donarmstrong.com>
Mon, 31 Oct 2016 22:14:56 +0000 (17:14 -0500)
array_to_excel.R [new file with mode: 0644]

diff --git a/array_to_excel.R b/array_to_excel.R
new file mode 100644 (file)
index 0000000..b818ca0
--- /dev/null
@@ -0,0 +1,35 @@
+### this requires txt2xls, which you can find here:
+### http://git.donarmstrong.com/bin.git/b/txt2xls
+
+mkdtemp <- function() {
+    max.tries <- 100
+    while (max.tries > 0) {
+        tmpnam <- tempfile("dir")
+        if (dir.create(tmpnam)) {
+            return(tmpnam)
+        }
+        max.tries <-  max.tries - 1
+    }
+    return(NA)
+}
+
+array_to_excel <- function(data,workbook) {
+    if (is.data.frame(data) || is.data.frame(data)) {
+        temp <- data
+        data <- list()
+        data[[workbook]] <-
+            temp
+    }
+    temp.dir <- mkdtemp()
+    worksheets <- NULL
+    for (worksheet in names(data)) {
+        write.table(data[[file]],
+                    file=file.path(temp.dir,worksheet))
+        worksheets <- c(worksheets,
+                        file.path(temp.dir,worksheet))
+    }
+    system("txt2xls","--output",workbook,worksheets)
+    unlink(worksheets)
+    unlink(temp.dir)
+    return(workbook)
+}