2012-08-28 12 views
13

Come si aprono rapidamente piccoli oggetti R tabella/vettoriali in Excel?Visualizza rapidamente un data.frame, vettoriale o data.table in Excel

Per esempio si supponga di avere le seguenti tre oggetti che si desidera visualizzare in Excel:

## A data frame with commas and quotes 
df = data.frame(
    area = unname(state.x77[,'Area']), 
    frost = unname(state.x77[,'Frost']), 
    comments = "Ok for a visit, but don't want to live there", 
    challengeComments = c('"', '""')) 
row.names(df) = state.name 
df = df[1:10, ] 
df['California', 'comments'] = "Would like to live here" 

## A Matrix 
mat = matrix(rnorm(100), 10) 

## A Vector 
v = 1:10 
+0

Ho scritto la domanda e la risposta come riferimento. Non sono sicuro che rispondere alla mia stessa domanda mi renda egocentrico o altruista. – geneorama

+0

Se si desidera visualizzare i dati in un foglio di calcolo come un modulo invece di aprire Excel, è possibile utilizzare 'fix',' edit', o 'data.entry' – Dason

+0

o' View' funziona anche – geneorama

risposta

13

Ho scritto questa funzione per realizzare questo compito. Lo chiamo "scrivi file temp" o "wtf". Funziona solo su Windows se hai file CSV associati ad Excel.

Si potrebbe guardare il codice in PBSmodelling :: openFile per vedere come adottarlo su diversi sistemi operativi.

wtf = function (x) { 
    tempFilePath = paste(tempfile(), ".csv") 
    tempPath = dirname(tempFilePath) 
    preferredFile = paste(deparse(substitute(x)), ".csv", sep = "") 
    preferredFilePath = file.path(tempPath, preferredFile) 

    if(length(dim(x))>2){ 
    stop('Too many dimensions') 
    } 
    if(is.null(dim(x))){ 
    x = as.data.frame(x) 
    } 
    if (is.null(rownames(x))) { 
    tmp = 1:nrow(x) 
    }else { 
    tmp = rownames(x) 
    } 
    rownames(x) = NULL 
    x = data.frame(RowLabels = tmp, x) 
    WriteAttempt = try(
    write.table(x, file=preferredFilePath, quote=TRUE, sep=",", na="", 
       row.names=FALSE, qmethod="double"), 
    silent = TRUE) 
    if ("try-error" %in% class(WriteAttempt)) { 
    write.table(x, file=tempFilePath, , quote=TRUE, sep=",", na="", 
       row.names=FALSE, qmethod="double") 
    shell.exec(tempFilePath) 
    } else { 
    shell.exec(preferredFilePath) 
    } 
} 


wtf(df) 
wtf(mat) 
wtf(v) 

se si apre lo stesso oggetto più volte, sarà ancora lavorare grazie alla gestione degli errori, ma avrà un nome temporaneo disordinato.

wtf(df) 
df$MoreData = pi 
wtf(df) 
+12

+1 per il nome della funzione –

+0

L'avete provato su sistemi operativi diversi da Windows? Inoltre: a seconda di quale WindowsOS e quale versione di Excel, questo potrebbe avviare più istanze dell'app Excel, piuttosto che aprire i file .csv in più finestre di un'istanza di Excel. Non è colpa tua (è di Redmond), ma scommetto che ci sono alcune eleganti chiamate di sistema che possono aggirare questi problemi. –

+0

"openFile" da PBSmodelling ha alcuni modi intelligenti per testare per quale sistema operativo si sta utilizzando. Ho capito che il desiderio di un collegamento R-Excel è principalmente qualcosa che gli utenti di Windows vogliono. – geneorama

0

Utilizzare write.csv(x, "clipboard") e incollare in Excel.

+0

Mi è piaciuta l'idea finché non l'ho provata. Sfortunatamente, incolla l'intera linea nella prima cella di ogni riga. Non inserisce automaticamente ciascun valore nella propria cella. – Farrel

+0

Ho dovuto usare "text to column" per la prima pasta e impostare il separatore corretto. Dopo di ciò, funziona bene per me (Excel 2007). La pasta successiva non ha bisogno di "text to column" qui. –

+0

Funziona per me, sebbene io usi OOo Calc. –

1

Scusate spudorata pubblicità ... È possibile provare il mio pacchetto http://cran.r-project.org/web/packages/excel.link/index.html Assomiglia:

library(excel.link) 
xlrc[a1]=df 

Dipende pacchetto Omegahat RDCOMClient quindi è necessario installarlo dai sorgenti:

install.packages("RDCOMClient", repos = "http://www.omegahat.org/R") 
install.packages("excel.link", repos = "http://cran.at.r-project.org",type="source") 
3

Ho scritto una funzione per aprire i file in Libre Office Calc o Excel. See here for details.

view <- function(data, autofilter=TRUE) { 
    # data: data frame 
    # autofilter: whether to apply a filter to make sorting and filtering easier 
    open_command <- switch(Sys.info()[['sysname']], 
          Windows= 'open', 
          Linux = 'xdg-open', 
          Darwin = 'open') 
    require(XLConnect) 
    temp_file <- paste0(tempfile(), '.xlsx') 
    wb <- loadWorkbook(temp_file, create = TRUE) 
    createSheet(wb, name = "temp") 
    writeWorksheet(wb, data, sheet = "temp", startRow = 1, startCol = 1) 
    if (autofilter) setAutoFilter(wb, 'temp', aref('A1', dim(data))) 
    saveWorkbook(wb,) 
    system(paste(open_command, temp_file)) 
} 
+0

Ho due correzioni a questa funzione molto utile, colui che lo rende in grado di gestire i dataset di dplyr, e l'altro specifica che la funzione XLConnect da utilizzare all'interno di questa funzione dovrebbe provenire dal pacchetto XLConnect, usando "::" -operatore. Questo perché ho avuto problemi con pacchetti in conflitto. Controlla il campo dei commenti nel link che Jeromy supporta, se hai avuto problemi con questa funzione. – emilBeBri

1

Uso questo spesso per incollare una tabella di dati in Excel:

write.table(x, "clipboard", row.names=F, sep='\t') 

E per copiare un (sotto) tabella da Excel in R, fare questo (assumendo che la tabella ha una riga di intestazione):

read.csv('clipboard', sep='\t') 
+0

Sì, adoro questo trucco e i delimitatori di tabulazione incollati direttamente in Excel. Il problema è il limite di memoria e la mancanza di supporto per Linux. Il mio pacchetto (geneorama) ha un clipper e ritagliato per incollare in e da Excel (da Excel a R non ha praticamente limiti di memoria btw). https://github.com/geneorama/geneorama/blob/master/R/clipper.R https://github.com/geneorama/geneorama/blob/master/R/clipped.R – geneorama

0

Ho scritto una funzione per Windows. Ma probabilmente funziona anche su altri sistemi operativi.

Crea file temporanei in C: \ Users \ ... \ Documents \ Rview e li apre con browseURL(). È possibile aprire fino a 99 file in parallelo. Puoi facilmente scegliere quali dimnames dovrebbero essere visualizzati dall'argomento "nomi". La funzione aggiungerà 'before +, -, = in col/rownames quindi verrà visualizzato correttamente in Excel.

Personalmente preferisco la soluzione utilizzando Sys.getenv ("TMP") sull'uso di tempfile() perché tempfile() farà confondere la cartella dei file temporanei dopo un certo periodo di tempo.

Vedere le descrizioni degli argomenti nella parte superiore del codice per ulteriori informazioni.

# This function creates a CSV file from a data.frame/matrix and opens it with the default CSV-opening-program 
# of the computer. 
# 
# x = data.frame/matrix 
# names = dimnames to be saved in the file. "col"=colnames, "rowcol"=rownames&colnames, "row"=rownames, "no"=no dimnames 
# nrows = maximum number of rows to be saved (for higher speed with large datasets) 
#   if n=-1, all rows will be displayed.-> see also the help for read.table() 
# ncols = maximum number of columns to be saved (for higher speed with large datasets) 
# folder = directory, where the temporary file should be saved. 
#   If NULL an accessible folder in C:/Users/.../Documents will be created automatically. 
# quote = should quotes be written into the csv File? -> see also the help for write.table() 
# na = how should NA values be displayed in the csv File? -> see also the help for write.table() 
# openfolder = Should the folder with all temporary files be opened after having created the file? 

view <- function(x, names=c("col","rowcol","row","no"), nrows=10000, ncols=1000, folder=NULL, quote=FALSE, na="NA", openfolder=FALSE, ...){ 

    names <- match.arg(names) 
    if(is.null(dim(x))) { 
    x <- as.matrix(x) 
    } 
    if(is.null(colnames(x))) colnames(x) <- paste0("V",1:ncol(x)) 

    if(nrows<0) nrows <- nrow(x) 
    if(ncols<0) ncols <- ncol(x) 
    # Shrink data.frame such that it can be saved & viewed faster. 
    nrows <- min(nrow(x), nrows) 
    if(nrows!=nrow(x)) x <- x[1:nrows,,drop=FALSE] 
    ncols <- min(ncol(x), ncols) 
    if(ncols!=ncol(x)) x <- x[,1:ncols,drop=FALSE] 


    # Define paths 
    # If is.null(folder), wird ein temporaerer Ordner im Windows-Dateisystem angelegt. 
    if(is.null(folder)) { 
    folder <- paste0(Sys.getenv("TMP"), "\\Rview") 
    suppressWarnings(dir.create(folder)) 
    } 

    # Wenn am Schluss des Pfades kein "/" angefuegt wurde, wird dies gemacht: 
    if(!substr(folder,nchar(folder),nchar(folder))%in%c("/","\\")) folder <- paste0(folder, "\\") 
    pfad0 <- folder 
    name <- "Rview_tmp" 
    nr <- "01" 
    csv <- ".csv" 

    # Check if there are existing files in the folder 
    fil <- list.files(pfad0) 
    # If there are no files in the folder, use the default save path. 
    if(length(fil)==0){ 
    pfad1 <- paste0(pfad0, name, nr, csv) 
    } else { 
    # Remove all files in the folder (if possible) 
    fil <- paste0(pfad0, fil) 
    suppressWarnings(try(file.remove(fil) , silent=TRUE)) 
    fil <- list.files(pfad0) 
    # If there are no files anymore use the default save path. 
    if(length(fil)==0) { 
     pfad1 <- paste0(pfad0, name, nr, csv) 
    } else { 
     # If there are sill files, read out the number of the newest file (with the highest number) 
     ncharfil <- nchar(fil) 
     mx <- max(as.numeric(substr(fil,ncharfil-5,ncharfil-4))) 
     # Add 1 to the number of the file 
     mxpl1 <- as.character(mx+1) 
     if(nchar(mxpl1)==1) mxpl1 <- paste0("0",mxpl1) 
     # Create a new path 
     pfad1 <- paste0(pfad0, name, mxpl1, csv) 
    } 
    } 

    # Rownames und colnames, die mit +, - oder = anfangen, mit ' am Anfang versehen, dass es von Excel richtig dargestellt wird 
    rn1 <- rownames(x) 
    cn1 <- colnames(x) 
    ind <- substr(rn1,1,1)%in%c("+","-","=") 
    if(any(ind)) rownames(x)[ind] <- paste0(" ",rn1[ind]) 
    ind <- substr(cn1,1,1)%in%c("+","-","=") 
    if(any(ind)) colnames(x)[ind] <- paste0(" ",cn1[ind]) 

    # Write CSV file & open. 
    if(names=="row") { 
    # If the first cell of the file is named "ID" Microsoft Excel warns that a SYLK file is opened. Therefore it is renamed. 
    if(rownames(x)[1]=="ID") rownames(x)[1] <- "lD" 
    write.table(x, file=pfad1, sep = ";", col.names=FALSE, row.names=TRUE, quote=quote, na=na, ...) 
    } else if (names=="col") { 
    # If the first cell of the file is named "ID" Microsoft Excel warns that a SYLK file is opened. Therefore it is renamed. 
    if(colnames(x)[1]=="ID") colnames(x)[1] <- "lD" 
    write.table(x, file=pfad1, sep = ";", col.names=TRUE, row.names=FALSE, quote=quote, na=na, ...) 
    } else if (names=="rowcol") { 
    write.table(x, file=pfad1, sep = ";", col.names=NA)     # Colnames & Rownames 
    } else { 
    write.table(x, file=pfad1, sep = ";", col.names=FALSE, row.names=FALSE, quote=quote, na=na, ...) 
    } 

    browseURL(pfad1) 
    if(openfolder) { 
    Sys.sleep(1) 
    browseURL(folder) 
    } 
} 
Problemi correlati