-
Notifications
You must be signed in to change notification settings - Fork 4
/
inout.Rmd
93 lines (65 loc) · 2.01 KB
/
inout.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
# Input / Output
We will learn how to:
* Read in a file
* Write out a file
* Save a graph in a file (Module 3)
## On vectors
* Read a file as a vector with the **scan** function
```{r, eval=F}
# Read in file
scan(file="file.txt")
# Save in object
k <- scan(file="file.txt")
```
By default, scans "double" (numeric) elements: it fails if the input contains characters.<br>
If non-numeric, you need to specify the type of data contained in the file:
```{r, eval=F}
# specify the type of data to scan
scan(file="file.txt",
what="character")
scan(file="~/file.txt",
what="character")
```
Regarding paths of files:<br>
If the file is not in the current directory, you can provide a full or relative path. For example, if located in the home directory, read it as:
```{r, eval=F}
scan(file="~/file.txt",
what="character")
```
* Write the content of a vector in a file:
```{r, eval=F}
# create a vector
mygenes <- c("SMAD4", "DKK1", "ASXL3", "ERG", "CKLF", "TIAM1", "VHL", "BTD", "EMP1", "MALL", "PAX3")
# write in a file
write(x=mygenes,
file="gene_list.txt")
```
Regarding paths of files:<br>
When you write a file, you can also specify a full or relative path:
```{r, eval=F}
# Write to home directory
write(x=mygenes,
file="~/gene_list.txt")
# Write to one directory up
write(x=mygenes,
file="../gene_list.txt")
```
## On data frames or matrices
* Read in a file into a data frame with the **read.table** function:
```{r, eval=F}
a <- read.table(file="file.txt")
```
You can convert it as a matrix, if needed, with:
```{r, eval=F}
a <- as.matrix(read.table(file="file.txt"))
```
Useful arguments:
<a href="https://sbcrg.github.io/CRG_RIntroduction/images/readtable.png"><img src="images/readtable.png" width="550/"></a>
* Write a data frame or matrix to a file:
```{r, eval=F}
write.table(x=a,
file="file.txt")
```
Useful arguments:
<a href="https://sbcrg.github.io/CRG_RIntroduction/images/readtable.png"><img src="images/writetable.png" width="550/"></a>
* Note that "\t" stands for tab-delimitation