-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSession1_R-intro.Rmd
More file actions
389 lines (315 loc) · 7.74 KB
/
Copy pathSession1_R-intro.Rmd
File metadata and controls
389 lines (315 loc) · 7.74 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
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
---
title: "R intro"
output:
pdf_document: default
html_notebook: default
---
#Version and directory
```{r}
#display the R version (plus the version of other attached packages)
sessionInfo()
```
```{r}
# print working directory
getwd()
```
```{r}
# this line itself will not print as it is commented, but the next line will print
print("this will be printed")
```
#Arithmetic operations
```{r}
#Arithmetic: +,-,/, * are called operators
2 + 2
2 - 2
15 / 2
5 * 4
2 + 2 *3
(2 + 2) * 3
```
#Variables
##A variable is any text (letter/word/alpha-numeric) which stores some value
##We use the assignment operator '<-' or '=' to pass a value to the variable
```{r}
# Variables
x <- 4
some_number <- 20
```
##Add two variables
```{r}
x+some_number
```
##Change the value of a variable
```{r}
x=100
x
x=x+2
x
```
#Vectors
##A vector is a collection of data elements
```{r}
some_vector1 <- c(1,2,3,4,5,6) # c is a 'function' that combines its arguments into a vector
some_vector1
some_vector2 <- 1:6 # a shortcut
some_vector2
series1 <- seq(from = 2, to = 20, by = 4) #series1 is a vector created by function seq
series1
```
```{r}
##how to get help on a function in R
?seq
```
```{r}
#we can perform operations on vectors such as addition, multiplication etc
x <- 1:5
x
y= x*2
y
```
```{r}
# add the two vectors
joined_vectors <- some_vector1 + some_vector2 # the vectors will be added element-wise
joined_vectors
```
## indexing and manipulating elements in a vector
## - Square brackets [ ] - used for indexing (position)
## - Parentheses () - used in functions to provide arguements
```{r}
x=seq(1,12,2)
x
```
```{r}
x[3] # 3 here is the index value, i.e 3rd element in x
x[c(3,4)]
## removing an element
x[-3] ## is x changed?
y= x[-4]
y
```
## searching for items in vectors
```{r}
# the which command will return the index (indices) of the value
x=c(1,7,6,5,4,9)
which(x == 7)
which(x > 5)
which(x == 3)
```
## minimum, maximum, mean, median
```{r}
max(x)
min(x)
range(x)
```
```{r}
which.max(x)
which.min(x)
```
```{r}
mean(x)
median(x)
```
## character vectors: Instead of numbers we use strings
```{r}
char_vec1 <- c("Maurice", "Jodi-Ann", "Essiet", "Brhan", "Jheannelle", "Layla")
char_vec1
char_vec1[3]
which(char_vec1=="Layla")
```
#Functions
##Functions are an operation or task performed on input 'arguments', which can be specified as variables
```{r}
## seq function is a build-in creating a series of numbers on the basis of specified parameters.
x <- seq(from = 2, to = 20, by = 4)
x
length(x) # length is a function
```
## Getting help
```{r}
?seq
```
#Data frames
##In any form of data analysis, it is important to understand the format of dataset(s).
##Data frames are form of data structures in tabular format. They are the most widely used format for data analysis in R.
##Data frames consist of:
##- rows : Observations
##- columns : Vectors of particular data types (such as character, integer,logical).
##Different columns can be of different datatype.
##Elements of same column must be same type
##Creating a data frame
```{r}
firstName <- c("Jheannelle","Jodi-Ann","Maurice","Brhan","Layla","Essiet") ## firstName is a Vector
lastName <- c("Johnson", "Richards", "Wade", "Gebremedhin", "Sana", "Ette")
Gender <- c("female", "female", "male", "male", "female","female")
id_no <- c(20,29,32,15,26,19)
Fav_icecream <- c("Vanilla","Strawberry","Pistachio","Chocolate","Vanilla","Chocolate")
ndcf_fellows <- data.frame(firstName, lastName, FullName=paste(firstName, lastName), Gender, id_no, Fav_icecream) # data.frame is a function to create a new data frame, ndcf_fellows is dataframe
ndcf_fellows
```
##Displaying features or data types within the data frame
```{r}
#summary(ndcf_fellows)
str(ndcf_fellows)
```
```{r}
class(Fav_icecream)
```
###Accessing columns in a data frame with $ notation
```{r}
ndcf_fellows
ndcf_fellows$FullName
```
##Tabulating entries in the data frame
```{r}
#ndcf_fellows$firstName
table(ndcf_fellows$Gender)
table(ndcf_fellows$Gender, ndcf_fellows$Fav_icecream)
```
##Writing the table to a csv file
```{r}
#save this table
write.csv(ndcf_fellows,"ndcf_fellows.csv")
```
##Reading a csv file into a data frame
```{r}
# open and read a csv file
ndcf_fellows2 <- read.csv("ndcf_fellows.csv", row.names = 1)
ndcf_fellows2
```
##Exploring data frames
```{r}
#Size
dim(ndcf_fellows) #returns number of rows and the number of columns
nrow(ndcf_fellows) # number of rows
ncol(ndcf_fellows) # number of columns
```
##Viewing parts of the data frame
```{r}
#Content
head(ndcf_fellows)
tail(ndcf_fellows)
colnames(ndcf_fellows)
rownames(ndcf_fellows)
#rownames(ndcf_fellows) <- ndcf_fellows$firstName
#rownames(ndcf_fellows)
```
##Summarize features in a data frame
```{r}
summary(ndcf_fellows)
```
##Indexing and subsetting data frames
##use [] bracketcs, [row position,column position]
```{r}
ndcf_fellows
```
```{r}
ndcf_fellows[2,]#extract entire row, which is a dataframe with single observation
```
```{r}
ndcf_fellows[2,3] # extract a particular element at row2 column3
```
##Column notation
```{r}
#Extract entire column, which is a vector
#ndcf_fellows$firstName
#ndcf_fellows[["firstName"]]
#ndcf_fellows[,"firstName"]
#ndcf_fellows[,"Gender"]
```
```{r}
#Extract particular cell
ndcf_fellows[4,6]
```
```{r}
#extract cell using column name
ndcf_fellows[4,"firstName"]
```
##Subset rows and columns
```{r}
# subsetting
#extract n number of rows
ndcf_fellows[c(1,2,4,6),]
```
```{r}
##extract some rows and columns
new_set<- ndcf_fellows[1:5,c("firstName","id_no", "Gender")]
new_set
```
```{r}
#extract rows based on some condition
ndcf_fellows[which(ndcf_fellows$Gender=="female"),]
```
```{r}
##make a new table with only female members
ndcf_fellows[which(ndcf_fellows$Gender=="female"),]
female_members <- ndcf_fellows[which(ndcf_fellows$Gender=="female"),]
female_members
```
##Exclusion notation
```{r}
#show everything except particular column
ndcf_fellows[,-1]
```
```{r}
#show everything except particular rows
ndcf_fellows[-c(1,3),]
```
##Text searching with grep
```{r}
###using Grep
## grep index values i.e.tell me the name of row numbers where the first name starts with 'J'
grep("^J", ndcf_fellows$firstName) # ^ is a regular expression also called regex in coding
```
```{r}
####subsetting with grep
firstnameL <- ndcf_fellows[grep("^J",ndcf_fellows$firstName),]
firstnameL
```
##change the values in data frame
```{r}
ndcf_fellows[4,5] <- "50"
ndcf_fellows
```
```{r}
# gsub function
ndcf_fellows$Fav_icecream <- gsub("Vanilla","GreenTea",ndcf_fellows$Fav_icecream )
ndcf_fellows
```
#Conditional statements and loops
```{r}
# open saved file
ndcf_fellows2 <- read.csv("ndcf_fellows.csv", row.names = 1)
ndcf_fellows2
```
##If statements
##These statements allow certain actions to be performed only if a statement is true
```{r}
if (nrow(ndcf_fellows2) > 10) {
print("There are more than 10 Fellows")
} else {
print("There are 10 or fewer Fellows")
}
```
```{r}
if (ndcf_fellows2$firstName[1]=="Layla") {
print("Layla is listed first in the table")
} else {
print("Someone other than Layla is listed first in the table")
}
```
##For loops
##These loops will run a block of code a certain number of times
```{r}
for (loopvariable in 1:5) {
print(loopvariable)
}
```
##More complex code in loop
```{r}
ndcf_fellows2$id_no=as.numeric(ndcf_fellows2$id_no)
ndcf_fellows2
for (var1 in 1:nrow(ndcf_fellows2)) {
ndcf_fellows2$id_no[var1]=2*ndcf_fellows2$id_no[var1]
}
ndcf_fellows2
```