-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path01 basics of R.R
More file actions
330 lines (254 loc) · 7.3 KB
/
Copy path01 basics of R.R
File metadata and controls
330 lines (254 loc) · 7.3 KB
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
3 + 4 # execute a line with Ctrl + Enter
# Results of any command will appear in the CONSOLE below
# Anything after a "#" symbol is ignored by R, so we can (and should!) use it to
# write comments.
#
# It is best to write your comments in English
# Variables ---------------------------------------------------------------
# Variables - an object which can vary...
# ASSIGN a value to an object with <- (shortcut alt+-)
# (it will now appear as an object in the ENVIRONMENT)
a <- 3
# Running code with only the name of an object results in R "printing" its
# contents to the CONSOLE:
a
# You can use the object just as you would its value:
a + 4
# Note that the value of "a" is not changed, and that the results were not saved
# anywhere
b <- 4
a + b
a * b
a <- 8
c <- a + b
c <- a * b
c <- b - a
c <- B - A # Your first ERROR. Why?
c <- a + b # assign without print
c # then print
# or
(c <- a + b) # assign and print at the same time
# More types of objects ------------------------------------------------
# character
chracter <- "sequence of characters (letters/ numbers/ symbols)"
Group1 <- "77"
Group2 <- "experimental"
Group1 / a
# numeric
a <- 3
b <- 4
# logical / boolean (TRUE/FALSE object)
a > b
b > a
a = 7
a == 7
a != 7
a < 10 & b > 8
a < 10 | b > 8
# `is.*()` functions can test if an object is of a certain type:
is.logical(a)
is.logical("TRUE")
is.logical(TRUE)
is.numeric(a)
is.character(a)
# Operators ---------------------------------------------------------------
# + addition
# - subtraction
# * multiplication
# / division
# ^ power
# %% modulo. The remainder after division. E.g., 5 %% 2 gives 1
# %/% integer division. E.g., 7 %/% 3 gives 2
# Order of operations
a + b / 2
a + (b / 2)
(a + b) / 2
# Math **functions**
# sqrt(x) square root
# abs(x) absolute value
# exp(x) exponent
# log(x) natural logarithm (e^log(x)=x)
# log10(x) (10^log10(x)=x)
# ceiling(x) round upwards
# floor(x) round downwards
# round(x) round to the nearest integer
# trunc(x) get rid of decimal digits
sqrt(a)
# Because we didn't assign the result into an object, it is lost forever.
# So if you want to use a result, DON'T FORGET: assign (<-) it!
sqrt_of_a <- sqrt(a)
# Get help on a function
?exp
# Vectors -----------------------------------------------------------------
# A vector is a "chain" of values
# You can "chain" values together with the `c()` function
math.grades <- c(93, 30, 84, 88, 100, 67)
english.grades <- c(100, 45, 90, 77, 88, 90)
# Some function work on or summarize a whole vector:
is.numeric(math.grades)
length(math.grades)
mean(math.grades)
sd(math.grades)
max(math.grades)
range(math.grades)
median(math.grades)
hist(math.grades)
# Some functions accept more than 1 ARGUMENT.
# For examples, these functions accept 2 arguments - both numeric vectors:
cor(math.grades, english.grades)
plot(math.grades, english.grades)
# QUIZ: What will these make?
pass.english <- english.grades >= 56
pass.english
sum(pass.english)
mean(pass.english) # NOTE the mean is equal to 5/6!
hebrew.grades <- c(100, NA, 99, 100, 80, 75)
# NA is "not available" - it is a way to mark missing data
is.na(hebrew.grades) # anyNA(hebrew.grades)
mean(hebrew.grades)
mean(hebrew.grades, na.rm = TRUE) # (na.rm = NA remove)
# here we used a second, named, argument.
# You can see all the arguments with:
?mean
?sd
# You can directly name all the arguments,
sd(x = hebrew.grades, na.rm = TRUE)
# But don't have to if they're in order
sd(hebrew.grades, TRUE)
# If you name the arguments, they can be in any order
sd(na.rm = TRUE, x = hebrew.grades)
sd(TRUE, hebrew.grades)
# Statistical distributions
rnorm(1) # random number generation from normal distribution (mean = 0, sd = 1)
rnorm(10)
?rnorm
# notice that each time we'll get another random number, to keep the same
# "random" number we can use set.seed()
x <- rnorm(1000)
hist(x)
x <- rnorm(1000, mean = 100, sd = 15)
hist(x)
x <- runif(1000)
hist(x)
x <- rexp(1000)
hist(x)
## Working with vectors ---------------------------------------------------
## Creating vectors
# Manually
v1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# a sequence
v2 <- 1:10
v3 <- seq(from = 2, to = 5, by = 0.5)
v4 <- seq(from = 1, to = 10, length = 3)
seq(from = 2, to = 11, length = 4)
seq_along(50:52) # creates a vector that contains a sequence of numbers from 1
# to the length of the object
seq_len(123) # generates a sequence from 1 to the specified number
# repeat a value
v5 <- rep(0, 10)
v5
# repeat multiple values
v6 <- rep(c(1, 2, 5), each = 10)
v7 <- rep(c(1, 2, 5), times = 10)
# chain vectors
c(v6, v7) # same as
c(rep(c(1, 2, 5), each = 10), rep(c(1, 2, 5), times = 10))
## Math operations on vectors
v8 <- v1 * 5
v9 <- v6 + v7
c(1, 2, 3, 4) + c(1, 2)
c(1, 2, 3, 4) + c(1, 2, 3)
## sample
v10 <- sample(v9, 40, replace = TRUE)
v10
set.seed(1)
v10 <- sample(v9, 40, replace = TRUE)
v10
## Extract and replace
# by index
v9[1]
v9[20:30]
i <- c(1, 3, 5)
v9[i]
v9[c(1, 3, 5)] # same
# order matters!
v9[c(1, 2, 3, 4)]
v9[c(4, 3, 1, 2)]
# What will this do?
v9[c(1, 2, 3, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
head(v9, 3)
tail(v9, 3)
v9[1]
v9[1] <- 100
v9[1]
v9[c(2, 4, 6)] <- -99
v9
# with a logical vector
v9[v9 > 6]
mean(v9[v9 > 6])
which(math.grades > 80 & math.grades <= 90)
math.grades
## naming vector elements
names(english.grades) <- c("noa", "tzipi", "avi", "shira", "yosi", "yarona")
english.grades
english.grades["shira"]
english.grades[4]
english.grades[9 %% 5]
# (reminder: modulo gives the remainder after division. E.g., 5 %% 2 gives 1)
french.grades <- c("anat" = 90, "yoav" = 100, "mattan" = 56)
mean(french.grades)
french.grades["anat"] + 2
## Factors ----------------------------------------------------------------
# A factor is a vector of CATEGORIES.
# Unlike a character vector, factors usually represent "levels"
set.seed(2)
(sex <- sample(c("M", "F"), size = 10, replace = TRUE))
x <- sex
x[4] <- "G"
factor(x, levels = c("M", "F"))
factor(sex, levels = c("M", "F")) # who cares about the order?
# for most cases it will not matter whether a factor is ordered or unordered if
# the factor is ordered, then the specific order of the levels matters (small <
# medium < large)
factor(sex, levels = c("m", "f")) # be careful...
factor(sex, levels = c("M"))
# Change the labels
factor(sex, labels = c("Female", "Male"))
#factor(sex, labels = c("Male", "Female"))
# Change labels *and* order of levels:
factor(sex, levels = c("M", "F"), labels = c("Male", "Female"))
# Lists -------------------------------------------------------------------
# What if you wanted to mix some types?
list1 <- c(100, "gugu", FALSE, "TRUE", 255)
str(list1)
# Use `list`!
list1 <- list(100, "gugu", FALSE, "TRUE", 255)
str(list1)
# each "value" in a list is an element.
# We can name elements
list2 <- list(
"Name" = "Beer-Sheva",
"Population" = 200000,
"is_negev" = TRUE
)
str(list2)
# We can now extract elements by their name:
list2[1] # accessing the first element
list2$Name # using name of access element
list2[["Name"]] # inner element of the specific name
list2["Name"]
list2[["Population"]] + 5
list2["Population"] + 5
list2[c("Name", "Population")]
# list with sub list (etc...)
list3 <- list(
"a" = 4,
"b" = c(2, 3),
"c" = list(1, 3, 5, T, "T")
)
str(list3)
list3[1] * 3
list3[[1]] * 3
list3[[3]][5]
list3[["c"]][[5]]
list3[["d"]] <- list3[["b"]] + 2