forked from CerebralMastication/R-Cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_InputAndOutput.Rmd
1631 lines (1173 loc) · 56 KB
/
04_InputAndOutput.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
```
```{r, echo=FALSE}
library(knitr)
hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
lines <- options$output.lines
if (is.null(lines)) {
return(hook_output(x, options)) # pass to default hook
}
x <- unlist(strsplit(x, "\n"))
more <- "etc ..."
if (length(lines)==1) { # first n lines
if (length(x) > lines) { # truncate the output, but add ....
x <- c(head(x, lines), more)
}
} else {
x <- c(more, x[lines], more)
}
# paste these lines together
x <- paste(c(x, ""), collapse = "\n")
hook_output(x, options)
})
```
# Input and Output {#InputAndOutput}
Introduction {-#intro-InputAndOutput}
------------
All statistical work begins with data, and most data is stuck inside
files and databases. Dealing with input is probably the first step of
implementing any significant statistical project.
All statistical work ends with reporting numbers back to a client, even
if you are the client. Formatting and producing output is probably the
climax of your project.
Casual R users can solve their input problems by using basic `readr` package functions
such as `read_csv` to read CSV files and `read_delim` to read more
complicated, tabular data. They can use `print`, `cat`, and `format` to
produce simple reports.
Users with heavy-duty input/output (I/O) needs are strongly encouraged
to read the R Data Import/Export guide, [available on CRAN](http://cran.r-project.org/doc/manuals/R-data.pdf). This manual
includes important information on reading data from sources such as
spreadsheets, binary files, other statistical systems, and relational
databases.
Entering Data from the Keyboard {#recipe-id035}
-------------------------------
### Problem {-#problem-id035}
You have a small amount of data, too small to justify the overhead of
creating an input file. You just want to enter the data directly into
your workspace.
### Solution {-#solution-id035}
For very small datasets, enter the data as literals using the `c`
constructor for vectors:
``` {r}
scores <- c(61, 66, 90, 88, 100)
```
### Discussion {-#discussion-id035}
When working on a simple problem, you may not want the hassle of creating
and then reading a data file outside of R. You may just want to enter the data into R.
The easiest way to do so is by using the `c` constructor for vectors, as shown
in the Solution.
You can use this approach for data frames, too, by entering each variable
(column) as a vector:
``` {r}
points <- data.frame(
label = c("Low", "Mid", "High"),
lbound = c(0, 0.67, 1.64),
ubound = c(0.67, 1.64, 2.33)
)
```
### See Also {-#see_also-id035}
For cutting and pasting data from another application into R, be sure to look at [`datapasta`](https://github.com/MilesMcBain/datapasta), a package that provides RStudio add-ins that make pasting data into your scripts easier.
Printing Fewer Digits (or More Digits) {#recipe-id036}
--------------------------------------
### Problem {-#problem-id036}
Your output contains too many digits or too few digits. You want to
print fewer or more.
### Solution {-#solution-id036}
For `print`, the `digits` parameter can control the number of printed
digits.
For `cat`, use the `format` function (which also has a `digits`
parameter) to alter the formatting of numbers.
### Discussion {-#discussion-id036}
R normally formats floating-point output to have seven digits. This works well most of the time but can become annoying when you have
lots of numbers to print in a small space. It gets downright misleading
when there are only a few significant digits in your numbers and R still
prints seven.
The `print` function lets you vary the number of printed digits using
the `digits` parameter:
``` {r}
print(pi, digits = 4)
print(100 * pi, digits = 4)
```
The `cat` function does not give you direct control over formatting.
Instead, use the `format` function to format your numbers before calling
`cat`:
``` {r}
cat(pi, "\n")
cat(format(pi, digits = 4), "\n")
```
This is R, so both `print` and `format` will format entire vectors at
once:
``` {r}
print(pnorm(-3:3), digits = 2)
format(pnorm(-3:3), digits = 2)
```
Notice that both `print` and `format` format the vector elements consistently, finding
the number of significant digits necessary to format the smallest number and then
formatting all numbers to have the same width (though not necessarily
the same number of digits). This is extremely useful for formating an
entire table:
``` {r}
q <- seq(from = 0, to = 3, by = 0.5)
tbl <- data.frame(Quant = q,
Lower = pnorm(-q),
Upper = pnorm(q))
tbl # Unformatted print
print(tbl, digits = 2) # Formatted print: fewer digits
```
As you can see, when an entire vector or column is formatted, each element in the vector or column is formatted the same way.
You can also alter the format of *all* output by using the `options`
function to change the default for `digits`:
``` {r}
pi
options(digits = 15)
pi
```
But this is a poor choice in our experience, since it also alters the
output from R’s built-in functions, and that alteration will likely be
unpleasant.
### See Also {-#see_also-id036}
Other functions for formatting numbers include `sprintf` and `formatC`;
see their help pages for details.
Redirecting Output to a File {#recipe-id034}
----------------------------
### Problem {-#problem-id034}
You want to redirect the output from R into a file instead of your
console.
### Solution {-#solution-id034}
You can redirect the output of the `cat` function by using its `file`
argument:
``` {r, eval=FALSE}
cat("The answer is", answer, "\n", file = "filename.txt")
```
Use the `sink` function to redirect *all* output from both `print` and
`cat`. Call `sink` with a `*filename*` argument to begin redirecting console
output to that file. When you are done, use `sink` with no argument to
close the file and resume output to the console:
``` {r, eval=FALSE}
sink("filename") # Begin writing output to file
# ... other session work ...
sink() # Resume writing output to console
```
### Discussion {-#discussion-id034}
The `print` and `cat` functions normally write their output to your
console. The `cat` function writes to a file if you supply a `file`
argument, which can be either a filename or a connection. The `print`
function cannot redirect its output, but the `sink` function can force all
output to a file. A common use for `sink` is to capture the output of an R
script:
``` {r, eval=FALSE}
sink("script_output.txt") # Redirect output to file
source("script.R") # Run the script, capturing its output
sink() # Resume writing output to console
```
If you are repeatedly `cat`ing items to one file, be sure to set
`append=TRUE`. Otherwise, each call to `cat` will simply overwrite the
file’s contents:
``` {r, eval=FALSE}
cat(data, file = "analysisReport.out")
cat(results, file = "analysisRepart.out", append = TRUE)
cat(conclusion, file = "analysisReport.out", append = TRUE)
```
Hardcoding filenames like this is a tedious and error-prone process.
Did you notice that the filename is misspelled in the second line?
Instead of hardcoding the filename repeatedly, we suggest opening a
connection to the file and writing your output to the connection:
``` {r, eval=FALSE}
con <- file("analysisReport.out", "w")
cat(data, file = con)
cat(results, file = con)
cat(conclusion, file = con)
close(con)
```
(You don’t need `append=TRUE` when writing to a connection because `append` is the default with connections.) This technique is especially valuable inside R scripts because
it makes your code more reliable and more maintainable.
Listing Files {#recipe-id030}
-------------
### Problem {-#problem-id030}
You want an R vector that is a listing of the files in your working directory.
### Solution {-#solution-id030}
The `list.files` function shows the contents of your working directory:
``` {r, output.lines=5}
list.files()
```
### Discussion {-#discussion-id030}
This function is terribly handy to grab the names of all files in a subdirectory. You can use it to refresh your memory of your filenames or, more likely, as input into another process, like importing data files.
You can pass `list.files` a path and a pattern to shows files in a specific path and matching a specific regular expression pattern.
```{r}
list.files(path = 'data/') # show files in a directory
list.files(path = 'data/', pattern = '\\.csv')
```
To see all the files in your subdirectories, too, use:
```{r, eval=FALSE, output=10}
list.files(recursive = T)
```
A possible “gotcha” of `list.files` is that it ignores hidden
files—typically, any file whose name begins with a period. If you don’t
see the file you expected to see, try setting `all.files=TRUE`:
``` {r}
list.files(path = 'data/', all.files = TRUE)
```
If you just want to see which files are in a directory and not use the filenames in a procedure, the easiest way is to open the Files pane in the lower-right corner of RStudio. But keep in mind that the RStudio Files pane hides files that start with a period, as you can see in Figure \@ref(fig:rstudio-files).
```{r rstudio-files, echo=FALSE, eval=TRUE, fig.cap="RStudio Files pane"}
knitr::include_graphics("images_v2/rstudio.files2.png")
```
### See Also {-}
R has other handy functions for working with files; see `help(files)`.
Dealing with “Cannot Open File” in Windows {#recipe-id033}
------------------------------------------
### Problem {-#problem-id033}
You are running R on Windows, and you are using filenames such as
`C:\data\sample.txt`. R says it cannot open the file, but you know the
file does exist.
### Solution {-#solution-id033}
The backslashes in the filepath are causing trouble. You can solve this
problem in one of two ways:
- Change the backslashes to forward slashes: `"C:/data/sample.txt"`.
- Double the backslashes: `"C:\\data\\sample.txt"`.
### Discussion {-#discussion-id033}
When you open a file in R, you give the filename as a character string.
Problems arise when the name contains backslashes (`\`) because
backslashes have a special meaning inside strings. You’ll probably get
something like this:
``` {r, eval=TRUE, error=TRUE}
samp <- read_csv("C:\Data\sample-data.csv")
```
R escapes every character that follows a backslash and then removes the
backslashes. That leaves a meaningless filepath, such as
`C:Datasample-data.csv` in this example.
The simple solution is to use forward slashes instead of backslashes. R
leaves the forward slashes alone, and Windows treats them just like
backslashes. Problem solved:
``` {r, eval=FALSE}
samp <- read_csv("C:/Data/sample-data.csv")
```
An alternative solution is to double the backslashes, since R replaces
two consecutive backslashes with a single backslash:
``` {r, eval=FALSE}
samp <- read_csv("C:\\Data\\sample-data.csv")
```
Reading Fixed-Width Records {#recipe-id136}
---------------------------
### Problem {-#problem-id136}
You are reading data from a file of fixed-width records: records whose
data items occur at fixed boundaries.
### Solution {-#solution-id136}
Use the `read_fwf` from the `readr` package (which is part of the tidyverse). The main arguments are the filename and the description of the fields:
``` {r, eval=FALSE}
library(tidyverse)
records <- read_fwf("myfile.txt",
fwf_cols(col1 = 10,
col2 = 7))
records
```
This form uses the `fwf_cols` parameter to pass column names and widths to the function. You can also pass column parameters in other ways as discussed next.
### Discussion {-#discussion-id136}
For reading data into R, we highly recommend the `readr` package. There are Base R functions for reading in text files, but `readr` improves on these base functions
with faster performance, better defaults, and more flexibility.
Suppose we want to read an entire file of fixed-width records, such as *fixed-width.txt*, shown here:
```
Fisher R.A. 1890 1962
Pearson Karl 1857 1936
Cox Gertrude 1900 1978
Yates Frank 1902 1994
Smith Kirstine 1878 1939
```
We need to know the column widths. In this case the columns are:
* Last name, 10 characters
* First name, 10 characters
* Year of birth, 5 characters
* Year of death, 5 characters
There are five different ways to define the columns using `read_fwf`. Pick the one that's easiest to use (or remember) in your situation:
* `read_fwf` can try to guess your column widths if there is empty space between the columns, with the `fwf_empty` option:
``` {r}
file <- "./data/datafile.fwf"
t1 <- read_fwf(file, fwf_empty(file, col_names = c("last", "first", "birth", "death")))
```
* You can define each column by a vector of widths followed by a vector of names with `fwf_widths`:
```{r}
t2 <- read_fwf(file, fwf_widths(c(10, 10, 5, 4),
c("last", "first", "birth", "death")))
```
* The columns can be defined with `fwf_cols`, which takes a series of column names followed by the column widths:
```{r}
t3 <-
read_fwf("./data/datafile.fwf",
fwf_cols(
last = 10,
first = 10,
birth = 5,
death = 5
))
```
* Each column can be defined by a beginning position and ending position with `fwf_cols`:
```{r}
t4 <- read_fwf(file, fwf_cols(
last = c(1, 10),
first = c(11, 20),
birth = c(21, 25),
death = c(26, 30)
))
```
* You can also define the columns with a vector of starting positions, a vector of ending positions, and a vector of column names, with `fwf_positions`:
```{r}
t5 <- read_fwf(file, fwf_positions(
c(1, 11, 21, 26),
c(10, 20, 25, 30),
c("first", "last", "birth", "death")
))
```
The `read_fwf` returns a *tibble*, which is a tidyverse flavor of data frame. As is common with tidyverse packages, `read_fwf` has a good selection of default assumptions that make it less tricky to use than some Base R functions for importing data. For example, `read_fwf` will, by default, import character fields as characters, not factors, which prevents much pain and consternation for users.
### See Also {-#see_also-id136}
See Recipe \@ref(recipe-id245), ["Reading Tabular Data Files"](#recipe-id245), for more discussion of
reading text files.
Reading Tabular Data Files {#recipe-id245}
--------------------------
### Problem {-#problem-id245}
You want to read a text file that contains a table of whitespace-delimited data.
### Solution {-#solution-id245}
Use the `read_table2` function from the `readr` package, which returns a tibble:
``` {r}
library(tidyverse)
tab1 <- read_table2("./data/datafile.tsv")
tab1
```
### Discussion {-#discussion-id245}
Tabular data files are quite common. They are text files with a simple
format:
- Each line contains one record.
- Within each record, fields (items) are separated by a whitespace
delimiter, such as a space or tab.
- Each record contains the same number of fields.
This format is more free-form than the fixed-width format because fields
needn’t be aligned by position. Here is the data file from Recipe \@ref(recipe-id136), ["Reading Fixed-Width Records"](#recipe-id136) in tabular format, using a
tab character between fields:
```
last first birth death
Fisher R.A. 1890 1962
Pearson Karl 1857 1936
Cox Gertrude 1900 1978
Yates Frank 1902 1994
Smith Kirstine 1878 1939
```
The `read_table2` function is designed to make some good guesses about your data. It assumes your data has column names in the first row, it guesses your delimiter, and it imputes your column types based on the first 1,000 records in your dataset. Next is an example with space-delimited data.
The source file looks like this:
```
last first birth death
Fisher R.A. 1890 1962
Pearson Karl 1857 1936
Cox Gertrude 1900 1978
Yates Frank 1902 1994
Smith Kirstine 1878 1939
```
And `read_table2` makes some rational guesses:
``` {r}
t <- read_table2("./data/datafile1.ssv")
print(t)
```
`read_table2` often guesses correctly. But as with other `readr` import functions, you can overwrite the defaults with explicit parameters.
``` {r}
t <-
read_table2(
"./data/datafile1.ssv",
col_types = c(
col_character(),
col_character(),
col_integer(),
col_integer()
)
)
```
If any field contains the string `"NA"`, then `read_table2` assumes that
the value is missing and converts it to NA. Your data file might employ
a different string to signal missing values, in which case use the
`na` parameter. The SAS convention, for example, is that missing
values are signaled by a single period (`.`).
We can read such text files using the `na="."` option.
If we have a file named *datafile_missing.tsv* that has a missing value indicated with a `.` in the last row:
```
last first birth death
Fisher R.A. 1890 1962
Pearson Karl 1857 1936
Cox Gertrude 1900 1978
Yates Frank 1902 1994
Smith Kirstine 1878 1939
Cox David 1924 .
```
we can import it like so:
``` {r}
t <- read_table2("./data/datafile_missing.tsv", na = ".")
t
```
We're huge fans of *self-describing* data: data files that describe their
own contents.
(A computer scientist would say the file contains its own metadata.)
The `read_table2` function makes the default assumption that the first line of your file contains a header line with column names.
If your file does not have column names, you can turn this off with the parameter `col_names = FALSE`.
An additional type of metadata supported by `read_table2` is comment lines. Using the `comment` parameter you can tell `read_table2` which character distinguishes comment lines. The following file has a comment line at the top that starts with `#`.
```
# The following is a list of statisticians
last first birth death
Fisher R.A. 1890 1962
Pearson Karl 1857 1936
Cox Gertrude 1900 1978
Yates Frank 1902 1994
Smith Kirstine 1878 1939
```
so we can import this file as follows:
``` {r}
t <- read_table2("./data/datafile.ssv", comment = '#')
t
```
`read_table2` has many parameters for controlling how it reads and
interprets the input file. See the help page (`?read_table2`) or the `readr` vignette (`vignette("readr")`) for more details. If you're curious about the difference between `read_table` and `read_table2`, it's in the help file... but the short answer is that `read_table` is slightly less forgiving in file structure and line length.
### See Also {-#see_also-id245}
If your data items are separated by commas, see
Recipe \@ref(recipe-id027), ["Reading from CSV Files"](#recipe-id027), for reading a CSV file.
Reading from CSV Files {#recipe-id027}
----------------------
### Problem {-#problem-id027}
You want to read data from a comma-separated values (CSV) file.
### Solution {-#solution-id027}
The `read_csv` function from the `readr` package is a fast (and, according to the documentation, fun) way to read CSV files. If your CSV file has a
header line, use this:
```{r, eval=FALSE}
library(tidyverse)
tbl <- read_csv("datafile.csv")
```
If your CSV file does not contain a header line, set the `col_names` option
to `FALSE`:
```{r, eval=FALSE}
tbl <- read_csv("datafile.csv", col_names = FALSE)
```
### Discussion {-#discussion-id027}
The CSV file format is popular because many programs can import and
export data in that format. This includes R, Excel, other
spreadsheet programs, many database managers, and most statistical
packages. It is a flat file of tabular data, where each line in the file
is a row of data, and each row contains data items separated by commas.
Here is a very simple CSV file with three rows and three columns. The
first line is a header line that contains the column names, also
separated by commas:
```
label,lbound,ubound
low,0,0.674
mid,0.674,1.64
high,1.64,2.33
```
The `read_csv` file reads the data and creates a tibble. The function assumes that your file has a header line unless told otherwise:
``` {r}
tbl <- read_csv("./data/example1.csv")
tbl
```
Observe that `read_csv` took the column names from the header line for
the tibble. If the file did not contain a header, then we would
specify `col_names=FALSE` and R would synthesize column names for us (`X1`,
`X2`, and `X3` in this case):
``` {r}
tbl <- read_csv("./data/example1.csv", col_names = FALSE)
tbl
```
Sometimes it's convenient to put metadata in files. If this metadata starts with a common character, such as a pound sign (`#`), we can use the `comment=FALSE` parameter to ignore metadata lines.
The `read_csv` function has many useful bells and whistles. A few of these options and their default values include:
`na = c("", "NA")`
: Indicates what values represent missing or NA values
`comment = ""`
: Indicates which lines to ignore as comments or metadata
`trim_ws = TRUE`
: Indicates whether to drop whitespace at the beginning and/or end of fields
`skip = 0`
: Indicates the number of rows to skip at the beginning of the file
`guess_max = min(1000, n_max)`
: Indicates the number of rows to consider when imputing column types
See the R help page, `help(read_csv)`, for more details on all the available options.
If you have a data file that uses semicolons (`;`) for separators and commas for the decimal mark, as is common outside of North America, you should use the function `read_csv2`, which is built for that very situation.
### See Also {-#see_also-id027}
See Recipe \@ref(recipe-id028), ["Writing to CSV Files"](#recipe-id028). See also the vignette for the `readr`: `vignette(readr)`.
Writing to CSV Files {#recipe-id028}
--------------------
### Problem {-#problem-id028}
You want to save a matrix or data frame in a file using the
comma-separated values format.
### Solution {-#solution-id028}
The `write_csv` function from the tidyverse `readr` package can write a CSV file:
``` {r, eval=FALSE}
library(tidyverse)
write_csv(df, path = "outfile.csv")
```
### Discussion {-#discussion-id028}
The `write_csv` function writes tabular data to an ASCII file in CSV format. Each row of data creates one line in the file, with data items separated by commas (`,`). We can start with the data frame `tab1` we created previously in Recipe \@ref(recipe-id245), ["Reading Tabular Data Files"](#recipe-id245).
``` {r}
library(tidyverse)
write_csv(tab1, "./data/tab1.csv")
```
This example creates a file called *tab1.csv* in the *data* directory, which is a subdirectory of the current working directory. The file looks like this:
``` {}
last,first,birth,death
Fisher,R.A.,1890,1962
Pearson,Karl,1857,1936
Cox,Gertrude,1900,1978
Yates,Frank,1902,1994
Smith,Kirstine,1878,1939
```
`write_csv` has a number of parameters with typically very good defaults. Should you want to adjust the output, here are a few parameters you can change, along with their defaults:
`col_names = TRUE`
: Indicates whether or not the first row contains column names.
`col_types = NULL`
: `write_csv` will look at the first 1,000 rows (changeable with `guess_max`) and make an informed guess as to what data types to use for the columns. If you'd rather explicitly state the column types, you can do so by passing a vector of column types to the parameter `col_types`.
`na = c("", "NA")`
: Indicates what values represent missing or NA values.
`comment = ""`
: Indicates which lines to ignore as comments or metadata.
`trim_ws = TRUE`
: Indicates whether to drop whitespace at the beginning and/or end of fields.
`skip = 0`
: Indicates the number of rows to skip at the beginning of the file.
`guess_max = min(1000, n_max)`
: Indicates the number of rows to consider when guessing column types.
### See Also {-#see_also-id028}
See Recipe \@ref(recipe-id008), ["Getting and Setting the Working Directory"](#recipe-id008), for more about the current working directory
and Recipe \@ref(recipe-id029), ["Saving and Transporting Objects"](#recipe-id029), for other ways to save data to files. For more info on reading and writing text files, see the `readr` vignette: `vignette(readr)`.
Reading Tabular or CSV Data from the Web {#recipe-id031}
----------------------------------------
### Problem {-#problem-id031}
You want to read data directly from the web into your R workspace.
### Solution {-#solution-id031}
Use the `read_csv` or `read_table2` functions from the `readr` package,
using a URL instead of a filename. The functions will read directly from the remote server:
``` {r}
library(tidyverse)
berkley <- read_csv('http://bit.ly/barkley18', comment = '#')
```
You can also open a connection using the URL and then read from the
connection, which may be preferable for complicated files.
### Discussion {-#discussion-id031}
The web is a gold mine of data. You could download the data into a file
and then read the file into R, but it’s more convenient to read directly
from the web. Give the URL to `read_csv`, `read_table2`, or another read function in `readr`
(depending upon the format of the data), and the data will be downloaded
and parsed for you. No fuss, no muss.
Aside from using a URL, this recipe is just like reading from a CSV file
(see Recipe \@ref(recipe-id027), ["Reading from CSV Files"](#recipe-id027)) or a complex file
(Recipe \@ref(recipe-id098), ["Reading Files with a Complex Structure"](#recipe-id098)), so all the
comments in those recipes apply here, too.
Remember that URLs work for FTP servers, not just HTTP servers. This
means that R can also read data from FTP sites using URLs:
``` {r, eval=FALSE}
tbl <- read_table2("ftp://ftp.example.com/download/data.txt")
```
### See Also {-#see_also-id031}
See Recipes \@ref(recipe-id027), ["Reading from CSV Files"](#recipe-id027), and \@ref(recipe-id098), ["Reading Files with a Complex Structure"](#recipe-id098).
Reading Data from Excel {#recipe-readexcel}
------------------
### Problem {-#problem-readexcel}
You want to read data in from an Excel file.
### Solution {-#solution-readexcel}
The `openxlsx` package makes reading Excel files easy.
```{r, eval=FALSE}
library(openxlsx)
df1 <- read.xlsx(xlsxFile = "file.xlsx",
sheet = 'sheet_name')
```
### Discussion {-#discussion-readexcel}
The package `openxlsx` is a good choice for both reading and writing Excel files with R. If we're reading in an entire sheet, passing a filename and a sheet name to the `read.xlsx` function is a simple option. We need only pass in a filename and, if desired, the name of the sheet we want imported:
```{r}
library(openxlsx)
df1 <- read.xlsx(xlsxFile = "data/iris_excel.xlsx",
sheet = 'iris_data')
head(df1, 3)
```
But `openxlsx` supports more complex workflows.
A common pattern is to read a named table out of an Excel file and into an R data frame. This is trickier because the sheet we're reading from may have values outside of the named table and we want to only read in the named table range. We can use the functions in `openxlsx` to get the location of a table, then read that range of cells into a data frame.
First we load the entire workbook into R:
```{r}
library(openxlsx)
wb <- loadWorkbook("data/excel_table_data.xlsx")
```
Then we can use the `getTables` function to get the names and ranges of all the Excel tables in the `input_data` sheet and select out the one table we want. In this example the Excel table we are after is named `example_data`:
```{r}
tables <- getTables(wb, 'input_data')
table_range_str <- names(tables[tables == 'example_table'])
table_range_refs <- strsplit(table_range_str, ':')[[1]]
# use a regex to extract out the row numbers
table_range_row_num <- gsub("[^0-9.]", "", table_range_refs)
# extract out the column numbers
table_range_col_num <- convertFromExcelRef(table_range_refs)
```
Now the vector `table_range_col_num` contains the column numbers of our named table, while `table_range_row_num` contains the row numbers.
We can then use the `read.xlsx` function to pull in only the rows and columns we want.
```{r}
df <- read.xlsx(
xlsxFile = "data/excel_table_data.xlsx",
sheet = 'input_data',
cols = table_range_col_num[1]:table_range_col_num[2],
rows = table_range_row_num[1]:table_range_row_num[2]
)
```
While this may seem complicated, this design pattern can save a lot of hassle when sharing data with analysts who are using highly structured Excel files that include named tables.
### See Also {-#see_also-readexcel}
Vignette for `openxlsx` by installing `openxlsx` and running: `vignette('Introduction', package='openxlsx')`
The [`readxl` package](https://readxl.tidyverse.org/) is part of the tidyverse and provides fast, simple reading of Excel files. However, `readxl` does not currently support named Excel tables.
The [`writexl` package](https://cran.r-project.org/web/packages/writexl/index.html) is a fast and lightweight (no dependencies) package for writing Excel files.
Recipe \@ref(recipe-writeexcel), ["Writing a Data Frame to Excel"](#recipe-writeexcel)
Writing a Data Frame to Excel {#recipe-writeexcel}
------------------
### Problem {-#problem-writeexcel}
You want to write an R data frame to an Excel file.
### Solution {-#solution-writeexcel}
The `openxlsx` package makes writing to Excel files relatively easy. While there are lots of options in `openxlsx`, a typical pattern is to specify an Excel filename and a sheet name:
```{r, message=FALSE, eval=FALSE}
library(openxlsx)
write.xlsx(df,
sheetName = "some_sheet",
file = "out_file.xlsx")
```
### Discussion {-#discussion-writeexcel}
The `openxlsx` package has a huge number of options for controlling many aspects of the Excel object model. We can use it to set cell colors, define named ranges, and set cell outlines, for example. But it has a few helper functions like `write.xlsx` that make simple tasks super easy.
When businesses work with Excel, it's a good practice to keep all input data in an Excel file in a named Excel table, which makes accessing the data easier and less error prone. However, if you use `openxlsx` to overwrite an Excel table in one of the sheets, you run the risk that the new data may contain fewer rows than the Excel table it replaces. That could cause errors, as you would end up with old data and new data in contiguous rows. The solution is to first delete an existing Excel table, then add new data back into the same location and assign the new data to a named Excel table. To do this we need to use the more advanced Excel manipulation features of `openxlsx`.
First we use `loadWorkbook` to read the Excel workbook into R in its entirety:
```{r, message=FALSE}
library(openxlsx)
wb <- loadWorkbook("data/excel_table_data.xlsx")
```
Before we delete the table, we want to extract the table's starting row and column.
```{r}
tables <- getTables(wb, 'input_data')
table_range_str <- names(tables[tables == 'example_table'])
table_range_refs <- strsplit(table_range_str, ':')[[1]]
# use a regex to extract out the starting row number
table_row_num <- gsub("[^0-9.]", "", table_range_refs)[[1]]
# extract out the starting column number
table_col_num <- convertFromExcelRef(table_range_refs)[[1]]
```
Then we can use the `removeTable` function to remove the existing named Excel table:
```{r}
removeTable(wb = wb,
sheet = 'input_data',
table = 'example_table')
```
Then we can use `writeDataTable` to write the `iris` data frame (which comes with R) to write data back into our workbook object in R.
```{r}
writeDataTable(
wb = wb,
sheet = 'input_data',
x = iris,
startCol = table_col_num,
startRow = table_row_num,
tableStyle = "TableStyleLight9",
tableName = 'example_table'
)
```
At this point we could save the workbook and our table would be updated. However, it's a good idea to save some metadata in the workbook to let others know exactly when the data was refreshed. We can do this with the `writeData` function, then save the workbook to a file and overwrite the original file. In this example, we'll put the metadata text in cell `B:5`, then save the workbook back to a file, overwriting the original.
```{r}
writeData(
wb = wb,
sheet = 'input_data',
x = paste('example_table data refreshed on:', Sys.time()),
startCol = 2,
startRow = 5
)
## then save the workbook
saveWorkbook(wb = wb,
file = "data/excel_table_data.xlsx",
overwrite = TRUE)
```
The resulting Excel sheet looks as shown in Figure \@ref(fig:excel-table).
```{r excel-table, fig.cap='Excel table and metadata text', echo=FALSE, eval=TRUE}
knitr::include_graphics("./images_v2/excel_table_data.png")
```
### See Also {-#see_also-writeexcel}
Vignette for `openxlsx` by installing `openxlsx` and running: `vignette('Introduction', package='openxlsx')`
The [`readxl` package](https://readxl.tidyverse.org/) is part of the tidyverse and provides fast, simple reading of Excel files.
The [`writexl` package](https://cran.r-project.org/web/packages/writexl/index.html) is a fast and lightweight (no dependencies) package for writing Excel files.
Recipe \@ref(recipe-readexcel), ["Reading Data from Excel"](#recipe-readexcel)
Reading Data from a SAS file {#recipe-readsas}
------------------
### Problem {-#problem-readsas}
You want to read a SAS dataset into an R data frame.
### Solution {-#solution-readsas}
The `sas7bdat` package supports reading SAS *sas7bdat* files into R.
```{r}
library(haven)
sas_movie_data <- read_sas("data/movies.sas7bdat")
```
### Discussion {-#discussion-readsas}
SAS V7 and beyond all support the *sas7bdat* file format. The `read_sas` function in `haven` supports reading the *sas7bdat* file format including variable labels. If your SAS file has variable labels, when they are inported into R they will be stored in the `label` attributes of the data frame. These labels will not be printed by default. You can see the labels by opening the data frame in RStudio, or by calling the `attributes` Base R function on each column:
```{r}
sapply(sas_movie_data, attributes)
```
### See Also {-#see_also-readsas}
The `sas7bdat` package is much slower on large files than `haven`, but it has more elaborate support for file attributes. If the SAS metadata is important to you, then you should investigate `sas7bdat::read.sas7bdat`.
Reading Data from HTML Tables {#recipe-id246}
-----------------------------
### Problem {-#problem-id246}