Copy an R data.frame to an Excel spreadsheet

后端 未结 3 1508
一个人的身影
一个人的身影 2021-02-02 08:39

I have a question which is exactly similar to this question.

As part of my work, I have to copy output from the R Studio Console to an excel worksheet in order to make e

相关标签:
3条回答
  • 2021-02-02 09:01

    From my experience there is no convenient way, I use two methods:

    For small data frames, use RStudio's View(data.frame) function, if you copy only data without headers it works fine, but if you want to copy with headers then you have to paste it into notepad first to add at least one character to the top left empty cell.

    For large data frames, use write.csv or write.xls (from package WriteXLS)

    0 讨论(0)
  • 2021-02-02 09:07

    It works with an easy trick.

    First, you have to visualize your data in the Viewer pane of Rstudio (you can use the function View()), then you should start selecting from the last value to the first, it is from bottom to top (see image). Note that the first cell should be selected completely. Finally, right click on the selection, copy, and then paste it in Excel as you want, with or without format.

    enter image description here

    Good luck!

    UPDATE:

    based on this Post, other alternative is making a new function to copy your data.frame to Excel through the clipboard:

    write.excel <- function(x,row.names=FALSE,col.names=TRUE,...) {
      write.table(x,"clipboard",sep="\t",row.names=row.names,col.names=col.names,...)
    }
    
    write.excel(my.df)
    

    and finally Ctr+V in Excel :)

    0 讨论(0)
  • 2021-02-02 09:15

    I usually source the following function:

    cb <- function(df, sep="\t", dec=",", max.size=(200*1000)){
        # Copy a data.frame to clipboard
        write.table(df, paste0("clipboard-", formatC(max.size, format="f", digits=0)), sep=sep, row.names=FALSE, dec=dec)
      }
    

    A few notes:

    • Max.size allows you to specify how big the clipboard can become (in kilobytes) before it cancels, it's set to ~200MB right now.
    • It works perfectly for copying an R dataframe from an R studio session to Excel (with my EU locale). You might have to adjust the separator / decimal symbols to make it work with US versions.

    How to use:

    df <- mtcars
    cb(df)
    # Paste in excel as 'values'
    
    0 讨论(0)
提交回复
热议问题