ROBDC SqlSave: How to export data into Excel sheets?
Вопрос
I'm trying to export data from R into one Excel file (into different sheets):
library(plyr)
library(RODBC)
g <- lapply(iris, function(x) as.data.frame(table(x)))
save2excel <- function(x) sqlSave(xlsFile,
x, tablename = x[1], rownames = FALSE)
xlsFile <- odbcConnectExcel("C:/Temp/iris.xls", readOnly = FALSE)
l_ply(g, save2excel)
odbcCloseAll()
This generates on error:
Error in sqlColumns(channel, tablename) :
‘1:35’: table not found on channel
The problem lies in tablename = x[1]
, how to get list names into sheet names?
Решение
You'll have to supply names(g)
to your function somehow. The simplest solution looks like mapply
.
Also, for whatever reason the Excel ODBC driver doesn't seem to like dots in sheet names, even though Excel itself can handle them. So you'll have to change your names like "Sepal.Length" to "Sepal_Length" or the like.
In full:
g <- lapply(iris, function(x) as.data.frame(table(x)))
names(g) <- gsub("\\.", "_", names(g))
xl <- odbcConnectExcel("c:/temp/iris.xls", readOnly=FALSE)
mapply(sqlSave, dat=g, tablename=names(g),
MoreArgs=list(channel=xl, rownames=FALSE))
odbcCloseAll()
Не связан с StackOverflow