-
Notifications
You must be signed in to change notification settings - Fork 1
/
03-memory.Rmd
123 lines (72 loc) · 2.42 KB
/
03-memory.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
# Memory {#memory}
Before we understand memory imprint in R. Lets start with a basic concept in functional programming.
1. Pure function
2. Impure function.
## Pure function
Any function that doesn't change the state of all objects in R and return the same value are called pure function.
```{r}
sqrt(2)
```
```{r}
log(2)
```
```{r}
names(mtcars)
```
functions like these are called pure function. They don't change anything at all and They return the same output given same input.
## Impure functions
And everything else is impure function. Functions like :
```{r}
rnorm(2)
```
```{r}
library(data.table)
```
```{r}
plot(mtcars)
```
library will load data.table or any package in R and then you can use it afterwards so it does change the current state of R and Plotting is impure for same reason. While rnorm will produce different result on same input every time.
All these functions Either don't give same output on same input or change the global environment in some way. This is crucial in understanding the next concept.
<br/>
***
There are 2 ways an element can be passed in a function.
1. pass by value
2. pass by reference
## Pass by value
Most of the function in R use pass by value. almost all the function in base R use pass by value. Where you create a copy of the object pass it in a function and then return the value out of it. for example read this code.
```{r}
a <- mtcars
b <- function(a){
a <- a[1,]
return(a)
}
b(a)
```
But it didn't change the actual a
```{r}
head(a)
```
in order to change the actual value of a we will have to pass it in a like this.
```{r}
a <- b(a)
a
```
now the a has been change permanently.
## Pass by reference
When you work on huge passing by value could sometime crash your programme. Thus data.table provide pass by reference in almost all of it's functions.
```{r}
a <- mtcars
setDT(a)
setnames(x = a,
old = names(a),
new = toupper(names(a)))
a[, b:= character(.N) ]
head(a)
```
I have a constantly in the previous example.
1. converted a from a data.frame to data.table
2. changed all the names from lowercase to uppercase.
3. added a new empty character column in a
and never in any of the statement have I used the assignment operator.
<br/>
These techniques are very beneficial when will learn about them later in other chapters. For the time being you must understand that data.table provides you an alternative to use your memory more effeciently.