Exporting data from R is mostly about choosing: - a destination path (folder), - a file name, - and a file format (extension).

In this lesson you will export a small summary table to: - CSV - Excel (.xlsx) - R data formats (.rds / .RData) - SPSS / SAS / Stata (via haven)

Working directory

If you write a file using only its name (e.g., "table_car.csv"), R saves it in the current working directory.

directory <- getwd()
directory
## [1] "/home/runner/work/An-R-Tutorial-for-Beginners/An-R-Tutorial-for-Beginners"

Tip: in projects (RStudio/Quarto), it is usually better to use project-relative paths (e.g., data/ or output/) rather than relying on the current working directory.

Create a data frame

We will start from mtcars and compute the mean of mpg and disp grouped by gear.

library(dplyr)

df <- mtcars |>
  dplyr::select(mpg, disp, gear) |>
  dplyr::group_by(gear) |>
  dplyr::summarise(
    mean_mpg  = mean(mpg),
    mean_disp = mean(disp),
    .groups = "drop"
  )

df
gear mean_mpg mean_disp
3 16.10667 326.3000
4 24.53333 123.0167
5 21.38000 202.4800

Note: dplyr::summarise() is written explicitly to avoid function-name conflicts during rendering (common in sites/books with many packages loaded).

Export to CSV

write.csv()

write.csv(df, "table_car.csv", row.names = FALSE)
  • row.names = FALSE avoids writing the row numbers as an extra column (often unwanted).

write.csv2() (semicolon-separated)

In some locales (common in Europe), Excel expects ; as separator and , as decimal mark. You can use:

write.csv2(df, "table_car.csv", row.names = FALSE)

Export to Excel (.xlsx)

Alternative (simple): writexl

If you only need to write data frames quickly (less styling/features than openxlsx), writexl is a lightweight choice:

writexl::write_xlsx(df, "table_car.xlsx")

Export to other statistical software (haven)

The haven package reads/writes common formats from SPSS, SAS, and Stata.

library(haven)

SPSS (.sav)

haven::write_sav(df, "table_car.sav")

SAS (.sas7bdat)

haven::write_sas(df, "table_car.sas7bdat")

Stata (.dta)

haven::write_dta(df, "table_car.dta")

Export R objects

RData (multiple objects)

save(df, file = "table_car.RData")
# load("table_car.RData")

Notes about “open folder”

Opening a folder from R (e.g., via system() / shell.exec()) may fail on servers and CI (GitHub Actions), so it’s safer to print the directory path and rely on the file browser of the environment. ```

 

A work by Gianluca Sottile

gianluca.sottile@unipa.it