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)
If you write a file using only its name (e.g.,
"table_car.csv"), R saves it in the current working
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.
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).
row.names = FALSE avoids writing the row numbers as an
extra column (often unwanted).The historical xlsx package depends on Java and
rJava, which can be painful on Mac/Linux/CI systems. A
smoother option is openxlsx (no Java), using
write.xlsx().
You can also export multiple sheets by passing a named list.
The haven package reads/writes common formats from SPSS, SAS, and Stata.
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