К save data to excel

R allows you to work with data and store it in variables in the workspace. However, sometimes you need you export or save to share or work with the results in other software. In this tutorial you will learn how to export data in R or RStudio. Note that you can export data from R to several formats, like CSV, SAV, XLS, XLSX, TXT or even XML.

  • 1 Save R objects
  • 2 Save data frame as CSV in R
  • 3 Export data from R to TXT file
  • 4 Export data from R to Excel (XLS and XLSX)
  • 5 Export to SPSS from R
  • 6 Save to STATA from R
  • 7 Export data from R to XML

Save R objects

When working with R, you can save the objects stored in your workspace. There are three main options, depending on if you want to save the full workspace, some objects or just one.

Exporting R objects from your workspace is very useful when your code takes a considerable amount of time to run, like in simulation studies. In consequence, if you need the results after the first execution you won’t need to run the code again.

First, you can export the full workspace from R with the save.image function as shown in the following block of code. Note that the output file will be of type RData.

# Export all objects (the workspace image)
save.image(file = "R_objects.RData")

Second, if you just need to export some objects you can specify them separated by comma with the save function.

# Export some R objects
save(x, y, file = "Two_Objects.RData")

Finally, to save only one object it is more recommended saving it as RDS with the saveRDS function:

# Export just one R object
saveRDS(x, file = "One_Object.rds")

If you specify compress = TRUE as argument of the previous functions the file will be compressed by default as gzip.

Save data frame as CSV in R

In case you want to export a data frame as CSV in R, you can make use of the write.csv or write.csv2 functions.

The use of one or the other will depend on the format of your data. In some countries they use a comma as decimal separator, so you can’t save a CSV separated by commas in this scenario. In this case, the CSV uses a semi-colon as separator of the data. The last is what the write.csv2 function does, while the write.csv uses a comma to separate the data. In consequence, you can export to CSV typing:

df <- data.frame(x = rnorm(10), y = rnorm(10))

# Comma as separator and dot as decimal separator
write.csv(df, "my_df.csv")

# Semi-colon as separator and comma as decimal separator
write.csv2(df, "my_df.csv")

Note you can also write a table to CSV in R with the same functions:

tb <- table(chickwts$feed)

write.csv(tb, "my_tb.csv")

write.csv2(tb, "my_tb.csv")

Recall to type ?write.csv or help(write.csv) for further information.

In this and the other functions of this tutorial, if you specify only the file name, the file will be saved in the working directory. If you want other location, change the working directory or specify the full path, instead of only the name of the file.

In order to export a TXT in R you can use the write.table function. Consider, for instance, that you want to export a data frame from R to a TXT file. In this case you could write:

df <- trees[1:5, ]

write.table(df, "file.txt")

However, if you want to print to the console what you are going to save, before saving it, you can type:

write.table(df)
   "Girth"  "Height"  "Volume"
"1"   8.3      70       10.3
"2"   8.6      65       10.3
"3"   8.8      63       10.2
"4"   10.5     72       16.4
"5"   10.7     81       18.8

Note that you can also export an R object, like a vector, to TXT with this function:

x <- runif(5)
write.table(x, "vector.txt")

If you save as TXT an R object different than a data frame or matrix, it will be coerced to a data frame.

In addition, there are several arguments you can customize. As an example, if you want to specify the encoding and to write the table without quotes you can type:

write.table(x, "vector.txt", fileEncoding = "UTF-8", quote = FALSE)

Export data from R to Excel (XLS and XLSX)

Exporting data from R to Excel can be achieved with several packages. The most known package to export data frames or tables as Excel is xlsx, that provides the write.xlsx and write.xlsx2 functions.

# Requires JAVA
# install.packages("xlsx")
library(xlsx)

# Comma as separator and dot as decimal separator
write.xlsx(x,                    # Data frame to be exported
           file,                 # Full path
           sheetName = "Sheet1", # Name of the sheet
           col.names = TRUE,     # Whether to include column names or not
           row.names = TRUE,     # Whether to include row names or not
           append = FALSE,       # Whether to append to an existing file
           showNA = TRUE,        # If TRUE, NA are empty cells
           password = NULL)      # Password as string

# Semi-colon as separator and comma as decimal separator
write.xlsx2(x, file, sheetName = "Sheet1", col.names = TRUE,
            row.names = TRUE, append = FALSE, showNA = TRUE, password = NULL)

As an example, if you want to save the cars dataset you can type:

write.xlsx(cars, "cars.xlsx")

However, the main disadvantage of the previous package is that requires JAVA installed on your computer, so if the JAVA_HOME is not specified or if R doesn’t find the rJava.dll file, the package won’t work.

Alternatives to export R output to XLSX that don’t require JAVA are the openxlsx and writexl packages:

On the one hand, the write.xlsx function of the openxlsx allows you to write a data frame or list of data frames to an XLSX file:

# install.packages("openxlsx")
library(openxlsx)

write.xlsx(data_frame, "file_name.xlsx")

On the other hand, the writexl library provides the write_xlsx function to export data frames in R to Excel:

# install.packages("writexl")
library("writexl")

write_xlsx(data_frame, "file_name.xlsx")

Export to SPSS from R

In case you want to export to SPSS from R you will need to install the package named haven, that contains the write_sav function. The process of saving the data is analogous to the others:

# install.packages("haven")
library(haven)

write_sav(mtcars, "mtcars.sav")

Save to STATA from R

In case you want export data from R to STATA, you will need to use the write.dta function of the foreign package as follows:

# install.packages("foreign")
library(foreign)

write.dta(data_frame, "my_data.dta")

Export data from R to XML

To easily export a dataframe to XML format you can use the write.xml function of the kulife package, indicating as first argument the dataset and the name of the exported file in the second. In this example we are going to save the mtcars dataset.

# install.packages("kulife")
library(kulife)

write.xml(mtcars, "mtcars.xml")
<?xml version="1.0"?>
<document>
  <row>
    <mpg>21</mpg>
    <cyl>6</cyl>
    <disp>160</disp>
    <hp>110</hp>
    <drat>3.9</drat>
    <wt>2.62</wt>
    <qsec>16.46</qsec>
    <vs>0</vs>
    <am>1</am>
    <gear>4</gear>
    <carb>4</carb>
  </row>

Nonetheless, you might have noticed that the XML output file does not contain the row names of the data frame, as the markup language doesn’t support naming the rows. To solve this issue, in this example you can bind the row names to the dataset and name the new column as “car”.

data <- cbind(rownames(mtcars), mtcars)
colnames(data)[1] <- "car"

write.xml(data, "mtcars.xml")
<?xml version="1.0"?>
<document>
  <row>
    <car>Mazda RX4</car>
    <mpg>21</mpg>
    <cyl>6</cyl>
    <disp>160</disp>
    <hp>110</hp>
    <drat>3.9</drat>
    <wt>2.62</wt>
    <qsec>16.46</qsec>
    <vs>0</vs>
    <am>1</am>
    <gear>4</gear>
    <carb>4</carb>
  </row>

Now, each row of the XML document will contain the name of the car and its characteristics.

It is a frequent requirement to save our dataframe for portability after working on it on the auxiliary memory of the computer system using R Programming Language. In this article, we will be using writexl package to export our dataframe to excel(.xlsx). The write_xlsx() function of the writexl package is used to export our dataframe to an Excel file.

Getting Started

The writexl is a simple package that contains a function write_xlsx() function which is used to write a dataframe to an Excel (.xlsx) file.

Installation

Packages are installed in R by using the install.packages() function. To install a package pass the name of the package/library to the install.packages() function. 

 We can install the writexl package by running the command below in the R console. 

install.packages("writexl")

Export the dataframe to excel

Example 1: In the first line of the code below, we have used library(“writexl”) function to load the package named -> “writexl”. We have then used write_xlsx() function of the writexl library to export the dataframe to an Excel file. In the below example, our write_xlsx() function takes 2 arguments, the first argument is the dataframe itself which is to be converted to an Excel file, the second argument is the path with “file_name.xlsx” which specifies the location where our Excel file will be saved with specified file_name.

To create a “.xlsx” with (multiple) named sheets, simply set “df” to a named list of data frames.

Syntax: write_xlsx(dataframe_name, “path\file_name.xlsx”)

Code:

R

library("writexl"

df <- data.frame(name = c("This", "is", "GFG"),

                 roll = c(10,20,30))

df

write_xlsx(df,"MY_PATHdf.xlsx")

Output:

 Our dataframe gets exported in the form of an Excel file to the specified location or path.

Example 2:

The only difference in this example from the previous examples is the arguments, in the example code below we have passed 2 extra arguments which help us have more control over the formatting of the Excel file. Those arguments and their usage are:

  • col_names: write column names at the top of the Excel file(.xlsx)
  • format_headers: make the column names(col_names) in the Excel file(.xlsx) centered and bold

Syntax:

write_xlsx(
  df,
  "path\file_name.xlsx"),
  col_names = TRUE,
  format_headers = TRUE
)

Code:

R

library("writexl"

df <- data.frame(name = c("This", "is", "GFG"),

                 roll = c(10,20,30))

df

write_xlsx(

        df,"My_path\df.xlsx",

        col_names = TRUE,

        format_headers = TRUE)

Output: 

Our dataframe gets exported in the form of an excel file to the specified location or path.

Export the dataframe to a CSV

The write.csv() is an inbuilt function in R, we do not require installing any additional library for using this function.

In the code below, our write.csv() function takes 2 arguments, the first argument is the dataframe itself which is to be converted to a CSV file, the second argument is the path with “file_name.csv” which specifies the location where our CSV file will be saved with specified file_name.

Syntax: write.csv(dataFrame_name, “path\file_name.csv”)

Code:

R

df <- data.frame(name = c("This", "is", "GFG"),

                 roll = c(10,20,30))

df

write.csv(df,"My_Path\df.csv")

Output: 

You can use the writexl package in order to export your DataFrame to Excel in R:

library("writexl")
write_xlsx(the dataframe name,"path to store the Excel file\file name.xlsx")

Step 1: Install the writexl package

You may type the following command in the R console in order to install the writexl package:

install.packages("writexl")

Follow the instructions to complete the installation. You may check the following guide for the steps to install a package in R.

Step 2: Create the DataFrame

Next, create the DataFrame that you’d like to export to Excel.

For example, let’s create a simple DataFrame with the following values:

df <- data.frame(Name = c("Jon", "Bill", "Maria", "Ben", "Tina"),
                 Age = c(23, 41, 32, 58, 26)
                 )
print (df)

This is how the DataFrame would look like in R:

   Name  Age
1   Jon   23
2  Bill   41
3 Maria   32
4   Ben   58
5  Tina   26

Step 3: Export the DataFrame to Excel in R

You may use the following template to assist you in exporting the DataFrame to Excel in R:

library("writexl")
write_xlsx(the dataframe name,"path to store the Excel file\file name.xlsx")

For our example:

  • The DataFrame name is: df
  • For demonstration, let’s assume that the path to store the Excel file is: C:\Users\Ron\Desktop\Test\people.xlsx
    • Where the file name to be created is people and the Excel file extension is xlsx

You’ll need to modify the path to reflect the location where you’d like to store the Excel file on your computer. You may also place double backslash (‘\’) within the path name to avoid any errors in R.

Here is the complete code for our example:

library("writexl")

df <- data.frame(Name = c("Jon", "Bill", "Maria", "Ben", "Tina"),
                 Age = c(23, 41, 32, 58, 26)
                 )

write_xlsx(df, "C:\Users\Ron\Desktop\Test\people.xlsx")

Once you run the code in R (adjusted to your path), the DataFrame would be exported to your specified location:

Name Age
Jon 23
Bill 41
Maria 32
Ben 58
Tina 26

You may also want to check the following guide for the steps to import an Excel file into R.

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of ‘sub-ids’ that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('aaa@aaa.com',3), rep('bbb@bbb.com', 3), rep('ccc@ccc.com', 3)))

So ids 1,2,3 would be associated with aaa@aaa.com. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I’m sure there’s more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "sender@sender.com",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Часто вас может заинтересовать экспорт фрейма данных pandas в Excel. К счастью, это легко сделать с помощью функции pandas to_excel() .

Чтобы использовать эту функцию, вам нужно сначала установить openpyxl , чтобы вы могли записывать файлы в Excel:

pip install openpyxl

В этом руководстве будет объяснено несколько примеров использования этой функции со следующим фреймом данных:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
 'assists': [5, 7, 7, 9, 12],
 'rebounds': [11, 8, 10, 6, 6]}) 

#view DataFrame
df

 points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6

Пример 1: базовый экспорт

В следующем коде показано, как экспортировать DataFrame по определенному пути к файлу и сохранить его как mydata.xlsx :

df.to_excel (r'C:UsersZachDesktopmydata.xlsx')

Вот как выглядит фактический файл Excel:

Пример 2: Экспорт без индекса

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False )

Вот как выглядит фактический файл Excel:

Пример 3: Экспорт без индекса и заголовка

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса и строку заголовка:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False, header= False )

Вот как выглядит фактический файл Excel:

Пример 4: Экспорт и имя листа

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и назвать рабочий лист Excel:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', sheet_name='this_data')

Вот как выглядит фактический файл Excel:

Полную документацию по функции to_excel() можно найти здесь .

Like this post? Please share to your friends:
  • К input data from excel
  • К initial word list
  • К controlled word list
  • К controlled word cards
  • Йога в word class