-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_workshop - script.R
executable file
·2321 lines (1646 loc) · 76.1 KB
/
_workshop - script.R
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
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
### ###
### Workshop: Basics in R for people who are afraid of computers ###
### DSh - VUB - May 2024 ###
### Rik Vosters - Vrije Universiteit Brussel ###
### Rik.Vosters@vub.be | www.rikvosters.be ###
### ###
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# 1. GETTING STARTED
# 2. BASIC VECTORS
# 2.1 Numeric vectors
# 2.2 Character vectors
# 3. DATAFRAMES, SUBSETTING AND DATA IMPORT
# 3.1 Data frames
# 3.2 Subsetting
# 3.3 Importing data
# 3.4 An alternative approach: tidyverse/dplyr
# 3.5 Other types of data structures
# 4. DATA CLEANING AND MANIPULATION
# 4.1 Data classes
# 4.2 Basic manipulations
# 4.3 Long and wide data
# 4.4 Merging datasets and working with metadata
# 4.5 Loading multiple files (loops and lapply)
# 5. ANALYZING TEXTUAL DATA
# 5.1 Loading text files
# 5.2 Basic text manipulation
# 5.3 Powersearching and regular expressions
# 5.4 Lemmatizing and POS tagging
# 5.5 Frequency lists
# 5.6 Keyness and word clouds
# 5.7 Concordances
# 6. DATA EXPLORATION AND VISUALIZATION
# 6.1 Preparation
# 6.2 Numerically summarizing - base package
# 6.3 Visualization - base package
# 6.4 Numerically summarizing - tidyverse/dplyr
# 6.5 Visualization - tidyverse/ggplot
# 7. BASIC STATISTICS
# 7.1 Distributions
# 7.2 Frequencies
# 7.3 Means
# 7.4 Correlations
### 1. GETTING STARTED -----
# How does R work?
# Type things in script and send to console
# "hello world"
print("hello world")
# Basic functions in R: addition, subtraction, etc.
2 + 7
2 * 7
2 + 9
# Notice how anything behind the hash is a comment and is not processed
2 + 7 # comment
2 + 7 # +100
2 + 7 + 100
# Assigning values
a <- 2 + 7 # assign (pro tip Mac: OPTION + '-')
# cf. 'Environment' window
a
# Alternative:
a = 2 + 7
# Operations on save values
a - 3
a <- a - 3 # overwrite
a
a <- a - 3; a # overwrite and display result
10 * a + (1 / 3 * a)
A # careful: R is case sensitive
# Define a sequence of elements (= vector)
b <- c(2, 4, 6) # notice: function c()
b
a + b
c <- c(a, b) # again, combine
c
# Some other basic functions
mean(c)
median(c)
min(b)
max(b)
plot(c) # plot -- cf. 'Plots' window
barplot(c)
# Embedded functions
plot(c(c, b)) # function combine inside function plot
barplot(c(mean(b), mean(c)))
# Syntax: three ways of writing it out
# most economical:
barplot(c(mean(b), mean(c)))
# most clear:
first_mean <- mean(b)
second_mean <- mean(c)
means_to_plot <- c(first_mean, second_mean)
barplot(means_to_plot)
# middle ground
means_to_plot <- c(mean(b), mean(c))
barplot(means_to_plot)
# Pro tip: use 'TAB' to autocomplete
# Typical structure of a function:
# function(x, y, option=FALSE)
# Need help?
?plot # cf. 'Help' window
?max()
?barplot()
# Starting routine
# clear working space
rm(list = ls(all = TRUE))
# set working directory
setwd("")
setwd("~/Dropbox/@ Documenten/Colleges - courses/_Gastcolleges/2024.05 DSh workshop - Basics in R/Basics-in-R")
getwd()
# Windows: setwd(choose.dir())
# Linux: tk_choose.files() does same thing - library(tcltk)
# also possible: CTRL + SHIFT + H
# also possible: RStudio Project
# Working with packages
# first, once:
install.packages("tidyverse")
# then, every session before using it or at the beginning of the script:
library(tidyverse)
# want to know more about the package?
help(package = tidyverse) # or write in 'Help' window
# install.packages("tidyverse") # once
library(tidyverse)
# alternatively:
# Packages > Install Packages | Tools > Install Packages
# Select a CRAN Mirror (Austria)
# Select a package or type the name of a package
# Use library(package) to load it
# see also: 'Packages' window
#### --- | exercise: create new file ---####
# - Create a new script file in RStudio (File > New file > R Script)
# - Enter the following in this new script file
# x <- c(1530, 1540, 1550, 1560, 1570, 1580, 1590, 1600)
# x
# y <- c(4, 9, 17, 48, 78, 92, 96, 98)
# y
# plot(x, y)
# - Save this file (File > Save as > …)
# - Now run your code: either line by line, or by selecting all
# of the lines and hitting 'CMD + enter' once
# (or clicking the 'Run' button in the toolbar at the top of your script file)
# - Go to the plot window, and save the plot you created
# (Export > Save plot as PDF > …; change the working directory if necessary)
# - Inspect the output you generated
#### --- | exercise: hours of sleep ---####
# - Assign values to create two vectors: one called 'sleep_week' where you input 5 numeric values for the (actual or fictitious) number of hours of sleep you got per weekday last week, and one called 'sleep_weekend' where you input 2 numeric values for the number of hours of sleep you got per day of the weekend last week. Make an estimation up to one decimal point (e.g. 8.5).
# - Create a new vector called 'weekend_zzz', for which you (automatically) calculate on average how many more hours of sleep you get in the weekend compared to during the week.
### 2. BASIC VECTORS -----
# empty workspace
rm(list = ls(all = TRUE))
# Most important data structures:
# Vectors: numeric, character, logical
# Dataframes (and tibble)
# Lists
### 2.1 Numeric vectors -----
# create a vector
vecky <- c(90, 95, 100, 105, 110)
vecky
# subsetting - access one specific element of that vector
vecky[1]
vecky[2:5]
vecky[c(2, 5)]
# generating vectors
1:35
1:1000
seq(from = 7, to = 9.5, by = 0.25)
rep(1:4, 3)
rep("abc", 3) # also for non-numerical vectors, cf. below
# some more data
wordcounts <- rnorm(100, mean = 180, sd = 40) # Generate 100 normally distributed
# data points with a standard deviation
# of 40 around a mean score of 180
wordcounts
# round
round(wordcounts, 0)
wordcounts <- round(wordcounts, 0)
wordcounts
# sort
sort(wordcounts)
sort(wordcounts, decreasing = T)
# visually
plot(wordcounts)
plot(sort(wordcounts))
hist(wordcounts)
# some other useful functions
length(wordcounts)
sum(wordcounts)
sum(wordcounts, vecky)
max(wordcounts)
min(wordcounts)
rev(wordcounts)
# more subsetting: logical expressions
wordcounts
sort(wordcounts, decreasing = T)
wordcounts[wordcounts >= 200] # gives you the actual elements from the
# dataframe matching the logical expression
# compare:
wordcounts >= 200 # logical vector
wordcounts[wordcounts >= 200]
# < Smaller than
# <= Smaller than or equal to
# > Larger than
# >= Larger than or equal to
# == Equal to
# != Unequal to
# is.na Has missing values (NA)
# !is.na Does not have missing values (not NA)
wordcounts[wordcounts != 210]
wordcounts[wordcounts >= 210]
wordcounts[is.na(wordcounts)] # to check if there are missing values
# how many elements in vector?
length(wordcounts[wordcounts >= 210])
wordcounts[wordcounts > 210 | wordcounts < 150] # | = OR
wordcounts[wordcounts < 175 & wordcounts > 150] # & = AND
benchmark <- 210:500 # define a vector with a benchmark range
benchmark
wordcounts[wordcounts %in% benchmark] # select all wordcount values
# that occur in that range
wordcounts[!wordcounts %in% benchmark] # select all wordcount values
# that do NOT occur in that range
#### --- | exercise: hours of sleep (bis) ---####
# 1. Empty the work space.
# 2. Create one vector with the (estimated) average hours of sleep you had for each night last week. Make an estimation up to one decimal point (e.g. 8.5), starting with Monday and ending with Sunday (i.e. 7 numbers in total)
# 3. Calculate your mean number of hours of sleep based on this vector. Round to two decimal points.
# 4. Calculate with a function how many nights you had less than 7 hours of sleep.
# 5. Calculate in how many percent of all nights last week you had 8 hours or more of sleep. (Tip: percent = (x/y)*100)
# 6. Calculate the difference between your average hours of sleep during the week (i.e. Monday night till Friday night) versus in the weekend (i.e. Saturday and Sunday night). Use a subset of the first 5 and the last 2 elements in your vector.
#### 2.2 Character vectors -----
# create a vector
vecky2 <- c("Colorless", "green", "ideas", "sleep", "furiously")
vecky2
vecky3 <- c("Time flies like an arrow", "Fruit flies like a banana")
vecky3
# no spaces in vector names - use underscore or dot
# vekkie test <- c("Aa", "Bb", "Cc")
vekkie_test <- c("Aa", "Bb", "Cc")
# subsetting - access one specific element of that vector
vecky2[1:3]
vecky2[c(2, 4)]
# stoplists
stoplist <- c("green", "linguistics", "sleep", "Chomsky") # define stoplist to test vector against for subsetting
vecky2 %in% stoplist # Does each element of vector vecky2 occur in
# the stoplist? (returns logical vector)
vecky2[vecky2 %in% stoplist] # Which elements of vecky2 occur in the stoplist?
vecky2[!vecky2 %in% stoplist] # Opposite: which elements of vecky2
# do not occur in stoplist?
# Useful for subsetting your corpus data or
# throwing out unwanted items (cf. later)
# other useful functions:
nchar(vecky2)
toupper(vecky2)
tolower(vecky2)
substr(vecky2, 1, 3)
# types and tokens
konami_code <- c("up", "up", "down", "down", "left", "right", "left", "right", "B", "A", "start")
konami_code
unique(konami_code) # types of the vector
table(konami_code) # type frequencies
sort(table(konami_code), decreasing = T) # sorted - basic frequency list!
# missing values = NA
konami_missing <- c("up", NA, "down", "down", "left", "right", "left", "right", "B", "A", "start")
table(konami_missing)
# numeric values missing
numbers <- c(1, 2, NA, 8, 12, NA, 36)
mean(numbers)
mean(numbers, na.rm = T)
#### --- | exercise: Belgian Dutch words ---####
# Below is a selection of words that are considered to be non-standard Belgian Dutch, according to one particular prescriptivist language advice guidebook. The actual list is longer, but we just show the words starting with the letters A and B for practical reasons.
# > "Afgevaardigd Beheerder", "Ajuin", "Alcoholieker", "Alleszins", "Ardeens", "Autostrade", "Autotaks", "Allergisch Aan", "Aftrekker", "Afkuisen", "Baxter", "Bedanking", "Bedelen", "Beenhouwer", "Begankenis", "Bekwaam Om", "Benadeligen", "Bereide Schotel", "Beschaamd", "Beteugelen", "Betoelagen", "Betonneren", "Betrachten", "Betrachting", "Betrouwen", "Bic", "Bijhuis", "Binnendoen", "Binnenkoer", "Baxter", "Botermelk", "Boerenbuiten", "Brol", "Brossen", "Buitensmijten", "Bureel"
# 1. Load the list of words into your workspace. Don't type all of them, but use copy and paste!
# 2. Convert the text to lower case.
# 3. Make a frequency table of the words in the list to check of there are no words accidentally listed twice.
# 4. If necessary, remove double words from the list.
# 5. Try to use subsetting to find our if the words 'beschaamd', 'bisser' and 'boterkoek' appear in the list of the non-standard Belgian Dutch words.
### 3. DATAFRAMES, SUBSETTING AND DATA IMPORT -----
# empty workspace
rm(list = ls(all = TRUE))
### 3.1 Data frames -----
# A dataframe consists of different vectors of the same length
col1 <- c("Aldrych", "Theobald", "Cadwell", "Ogden", "Roderick", "Rypley", "Marston", "Jimmy")
col2 <- c("/r/", "/R/", "/R/", NA, "/r/", "/r/", "/R/", "/R/")
col3 <- c(21, 98, 46, 17, 91, 100, 76, 0)
col4 <- c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE)
# Combining these three vectors with the function data.frame gives us one dataframe called 'OE'
OE <- data.frame(col1, col2, col3, col4)
# You can add column names (= Variable names) to the dataframe
names(OE) <- c("Scribe", "Pronunciation", "Reaction_time", "Verified")
OE # access entire dataframe
### 3.2 Subsetting -----
# Subsetting: same logic, but two dimensions: [rows, columns]
OE
OE[1, ] # first row of dataframe OE
OE[, 1] # first column of dataframe OE; same as:
# same, but easier (columns)
OE$Scribe
OE$Reaction_time
OE[, 1:3] # what will we get here?
OE[3:6, 1] # and here?
OE[3:6,]$Scribe
OE$Scribe[3:6]
# Functions: Functions operating on vectors also work on columns/factors in a data frame
# … both numerical:
mean(OE$Reaction_time)
plot(sort(OE$Reaction_time))
# … and character-based:
toupper(OE$Scribe)
table(OE$Pronunciation)
# More subsetting: we can also subset the whole dataframe based on selection criteria applied to specific factors
OE[OE$Reaction_time > 25, ] # Subset the dataframe OE with all the entries
# (rows) which have a reaction time of more than 25
# Mind the comma!
OE[OE$Scribe != "Roderick", ]
OE[OE$Reaction_time > 25 & OE$Pronunciation == "/r/", ]
# head() # cf. tail()
# see only first 6 rows
head(OE) # identical as OE[1:6,]
head(OE, 3) # specify number of rows
### 3.3 Importing data -----
# Several methods, depending on format of source
# TYPE 1: CSV - comma-separated (text) files
# be sure to set the working directory (or give a full path)
setwd("/Users/rikvosters/Dropbox/@ Documenten/Colleges - courses/_Gastcolleges/2024.05 DSh workshop - Basics in R/Basics-in-R")
# load
shark <- read.csv("SharkAttacks_sample.csv") # based on: https://data.world/shruti-prabhu/shark-attacks
head(shark)
# options:
read.csv("SharkAttacks_sample.csv", header = T, sep = ",", na.strings = "", encoding = "UTF-8", strip.white = T, dec = ".")
# separator value = often '\t' (tab-delimited)
# also: read.delim() instead of read.csv
# alternative:
# - Import tool in RStudio:
# `File` > `Import dataset` > `From Text (base)`
# TYPE 2: Internet files with a specific URL
shark <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/SharkAttacks_sample.csv") # no need to set working directory
head(shark)
# TYPE 3: Excel spreadsheets
library(readxl) # first (just once): install.packages(readxl)
read_excel("SharkAttacks.xlsx")
# loads it as special type of dataframe: tibble (cf. infra)
# TYPE 4: R package
# some data is just available in a ready-made R package
# e.g. baby names
library(babynames) # first (just once): install.packages("babynames")
bb <- babynames
bb # also tibble
#### --- | exercise: LEGO ---####
# Load a dataset called 'LEGOsets.csv', which contains an overview of all official LEGO sets (source: https://www.kaggle.com/rtatman/lego-database). You can either load it from the workshop folder, or from an online url (https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/LEGOsets.csv). Explore the first six rows of the dataframe. Then make a histogram of the variable 'year', to see how many sets were released each year. Next, check with a function when the first official set was released. Finally, extract the names of all LEGO sets released in 1955.
#### --- | exercise: negation ---####
# Load a dataset called 'negation.csv' (https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/negation.csv). It contains an entry for each linguistic expression of negation in a corpus of early 19th century Flemish soldiers' letters. Negation either occur with a 'Single' negator, or as 'Bipartite' negation (i.e. with two negators). First use table() to check out what the distribution of Single versus Bipartite negation tokens is. Then work with a subset to find out if either form of negation occurs more often in main clauses with a SVO word order (Subject-Verb-Object), compared to subclauses with a SOV order (Subject-Object-Verb).
#### --- | exercise: catholic fertility ---####
# Install and load the dataset 'swiss':
# helvetica <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/swiss.csv")
# This dataset contains Swiss fertility and socioeconomic indicators from the year 1888. Save this dataset in your working environment as a new dataframe called 'helvetica', and explore it by looking at the first 10 rows. Now extract the rows only for those districts where more than 50% of the population is catholic, and calculate the mean fertility rate for these predominantly catholic districts. Now compare it to the mean fertility rate of districts with 50% of catholics or less.
### 3.4 An alternative approach: tidyverse/dplyr -----
# new kid on the block: tidyverse (tidyverse.org)
# popular set of packages (dplyr, ggplot, tidyr, ... )
# easier to get started, but harder for some things
# 'tidy' data:
# 1. each column is a variable
# 2. each row is an observation
library(tidyverse) # only once: install.packages("tidyverse")
# Some innovations:
# 1. Tibbles instead of dataframes
bb <- babynames
bb
# faster and easier to work with; always prints 10 cases and as many columns as fit on screen
# to see more:
print(bb, n = 50)
# possible to make a dataframe into a tibble:
OE_tibble <- tibble(OE)
OE_tibble
# and back
OE <- data.frame(OE_tibble)
OE
# 2. Pipe character %>%
# generate some data data
wordcounts <- rnorm(100, mean = 180, sd = 40)
# for sequential code rather than embedded functions (CMD + shift + M)
wordcounts %>%
sort() %>%
plot()
# is the same as:
plot(sort(wordcounts))
round(mean(babynames$n))
# is the same as:
babynames$n %>% # CTRL/CMD + SHIFT + M
mean() %>%
round()
# 3. 'Plying' your data (dplyr)
# filter(): similar to subsetting, selecting cases (rows) based on their values
babynames %>%
filter(name == "Dwight")
babynames[babynames$name == "Dwight",]
babynames %>%
filter(name == "Dwight") %>%
filter(sex == "M")
# often serves as input for a plot (ggplot: see later)
babynames %>%
filter(name == "Dwight") %>%
filter(sex == "M") %>%
ggplot(aes(x = year, y = prop)) +
geom_line()
# possibility to match more flexibly (e.g. regular expressions)
babynames %>%
filter(str_detect(name, "Adol")) %>%
filter(sex == "F")
# mutate(): add new variables (columns)
babynames %>%
mutate(prop_overall = n / sum(n))
babynames %>%
mutate(name_gendered = paste0(name, "_", sex))
# to save new/modified tibble:
babynames %>%
mutate(prop_overall = n / sum(n)) -> babynames
# same as:
babynames <- babynames %>%
mutate(prop_overall = n / sum(n))
# select(): select variables (columns)
babynames %>%
select(year, sex, name)
# arrange(): change order of cases (rows)
babynames %>%
filter(year == 1950) %>%
arrange(name, sex)
babynames %>%
filter(year == 1950) %>%
arrange(desc(name), sex)
# combine multiple dplyr functions
# most popular boy's names in 1945
babynames %>%
filter(year == 1945) %>%
filter(sex == "M") %>%
arrange(desc(prop))
# popularity of name 'Adolf'
babynames %>%
filter(name == "Adolf") %>%
filter(sex == "M") %>%
ggplot(aes(x = year, y = prop)) +
geom_line() +
geom_vline(xintercept = 1940, color = "red")
# tally(): check how many cases/rows left after filter (similar to length)
babynames %>%
filter(str_detect(name, "Adol")) %>%
filter(sex == "F") %>%
select(name) %>%
unique()
babynames %>%
filter(str_detect(name, "Adol")) %>%
filter(sex == "F") %>%
select(name) %>%
unique() %>%
tally() # equivalent to length()
#### --- | exercise: shark attacks ---####
# Load and explore the data on shark attacks from the internet (https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/SharkAttacks.csv). It is a tab separated file, so be sure to use the argument sep="\t". Also, it uses quotation marks in the text, so add the argument quote="". Browse through this dataset of almost 6000 documented shark attackes in history and try to answer the following questions, using either the base R package or tidyverse/dplyr:
# - How many people died of a shark attack in 2017?
# - Check if more shark attacks occurred in the 10 years before the movie Jaws came out in 1975, compared to 10 years after Jaws.
# - How old was the oldest Australian every to die from a shark attack?
# - Extract the names of all New Zealand victims of shark attacks in the 20th century, under the age of 16.
read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/SharkAttacks.csv", sep = "\t", quote = "")
### 3.5 Other types of data structures -----
# matrix
matrix(1:20, nrow = 5, ncol = 4)
# list
names <- c("Samwise", "Meriadoc", "Peregrin", "Gimli", "Legolas")
hobbit <- c(TRUE, TRUE, TRUE, FALSE, FALSE)
age <- c(38, 36, 28, 139, 572, 6782, 18)
# compare
data.frame(names, hobbit, age)
list(names, hobbit, age)
# the power of lists: different lengths
sample_list <- list(een = c(1, 2, 3), twee = c(1999, 2000, 2001, 2002, 2003), drie = c("A", "B", "C", "D", "E", "F"))
sample_list
# subsetting
sample_list[[2]]
sample_list[[2]][1]
### 4. DATA CLEANING AND MANIPULATION -----
# empty workspace
rm(list = ls(all = TRUE))
# load packages
library(tidyverse)
# New dataset: Dogs of Zuerich (https://www.kaggle.com/kmader/dogs-of-zurich)
# Data about Dog Owners in Zuerich, Switzerland
dog <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/DogsOfZuerich.csv", sep = ";", na.strings = "")
head(dog)
### 4.1 Data classes -----
names <- c("Samwise", "Meriadoc", "Peregrin", "Gimli", "Legolas")
age <- c(38, 36, 28, 139, 572)
hobbit <- c(TRUE, TRUE, TRUE, FALSE, FALSE)
# basic data classes:
class(names)
class(age)
class(hobbit)
class(dog)
# also on columns in dataframes
class(dog$BIRTHYEAR)
class(dog$COLOR)
# character versus factor
dog$OWNER_SEX <- as.factor(dog$OWNER_SEX)
dog$OWNER_SEX
# cf. as.numeric(), as.character(), etc.
# fyi: convert all character vectors in dataframe to factors:
# dog %>% mutate_if(is.character, as.factor) -> dog
# levels
levels(dog$OWNER_SEX)
table(dog$OWNER_SEX)
barplot(table(dog$OWNER_SEX))
### 4.2 Basic manipulations -----
# reorder factor levels: fct_relevel()
levels(dog$OWNER_SEX)
dog$OWNER_SEX <- factor(dog$OWNER_SEX, levels = c("w", "m"))
levels(dog$OWNER_SEX)
barplot(table(dog$OWNER_SEX))
# alternative (even easier):
fct_relevel(dog$OWNER_SEX, "w", "m")
dog$OWNER_SEX <- fct_relevel(dog$OWNER_SEX, "w")
# rename factor levels: fct_recode()
dog$OWNER_SEX <- fct_recode(dog$OWNER_SEX, "female" = "w", "male" = "m") # new = old
dog$OWNER_SEX
dog$OWNER_AGE <- as.factor(dog$OWNER_AGE)
levels(dog$OWNER_AGE) # problem: Excel made '11-20' into '44136' (thinking it was a date)
dog$OWNER_AGE <- fct_recode(dog$OWNER_AGE, "11-20" = "44136")
levels(dog$OWNER_AGE) # solved (but reorder needed!)
dog$OWNER_AGE <- fct_relevel(dog$OWNER_AGE, "11-20") # no need to list the rest
levels(dog$OWNER_AGE)
# make infrequent values into 'other': fct_lump()
# several possibilities:
# fct_lump_n() # lump all except n most frequent items
# fct_lump_min() # lump all items that appear less than min times
sort(table(dog$BREED), decreasing = T) # sorted frequency table
# fct_lump_n
dog$BREED_rcd <- fct_lump_n(dog$BREED, n = 15)
sort(table(dog$BREED_rcd), decreasing = T)
# fct_lump_min
dog$BREED_rcd <- fct_lump_min(dog$BREED, min = 50)
sort(table(dog$BREED_rcd), decreasing = T)
# replace text: gsub()
class(dog$BREED)
table(dog$BREED)
dog$BREED <- gsub("Zwerg", "Miniature ", dog$BREED)
table(dog$BREED)
# transform data: mutate()
table(dog$BIRTHYEAR)
dog %>%
mutate(AGE = 2016 - BIRTHYEAR) -> dog
table(dog$AGE)
table(dog$BIRTHYEAR)
dog$AGE <- 2016 - dog$BIRTHYEAR
table(dog$AGE) # dogs 36 and 54 years old ≠ possible!
# remove extreme or unlikely values: filter()
dog %>%
filter(AGE < 30) -> dog
table(dog$AGE)
hist(dog$AGE)
# reorder rows: arrange()
head(dog) # order by dog age instead of ID
dog %>%
arrange(AGE) -> dog
head(dog)
# change column names: rename()
dog %>%
rename(OWNER_GENDER = OWNER_SEX) -> dog
head(dog)
# change column order: relocate()
dog %>%
relocate(AGE) -> dog # AGE to the left
head(dog)
dog %>%
relocate(ID) -> dog # ID back to the left
head(dog)
dog %>%
relocate(AGE, .after = BIRTHYEAR) -> dog # age to the right of birthyear
head(dog)
# random subset: sample_n()
dog_sample <- sample_n(dog, 1000)
#### --- | exercise: dogs of Zuerich ---####
# Reload the Dogs of Zuerich csv file (https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/DogsOfZuerich.csv). Recode the 'TYPE_BREED' variable into a new 'SIZE' variable. 'K' stands for 'Kleinwüchsig' and represents small dogs, while 'I' and 'II' stand for 'Rassentypenliste I' and 'II', representing larger dogs. Check the proportion of small versus large dogs in Zurich, and check if women are more likely to have small dogs than men. Finally, if you have to buy a dog for your 85 year old grandmother, what specific breed would have the highest probability of her liking it, given her age and gender?
dog <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/DogsOfZuerich.csv", sep=";", na.strings = "")
### 4.3 Long and wide data -----
# 1. Wide to long
# let's load a new data set, with population data of some countries from 1960 to 2015
pop <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/world_population_wide.csv",
sep = ",", check.names = F)
pop <- tibble(pop)
# we need another package from the Tidyverse, which is not part of the main 'tidyverse' library
library(tidyr) # once: install.packages("tidyr")
# currently in wide format
pop
# what we want and need for some applications (e.g. plots in ggplot) is a long data format:
# three columns: Country, Year and Population
# so that we can e.g. filter(Year == ...) (which is now not possible, as these are columns and not rows)
pop %>%
pivot_longer(cols = `1960`:`2015`,
names_to = "Year",
values_to = "Population") -> popl
popl$Year <- as.numeric(popl$Year)
popl
# now easy filtering....
popl %>%
filter(Year == 2000)
# ... and easy plotting (cf. later)
popl %>%
filter(Country %in% c("China", "India", "United States", "Serbia", "United Kingdom")) %>%
ggplot(aes(x = Year, y = Population, col = Country)) +
geom_line()
# 2. Long to wide
# sometimes useful for easier/more visual summary
library(babynames)
bb <- babynames
bb %>%
filter(name %in% c("Izzy", "Ricky", "Archie", "Eli", "Leo", "Freddy", "Tony", "Randy", "Frankie", "Rudy")) %>%
filter(year >= 2010) %>%
filter(sex == "M") %>%
select(year, name, n) -> bb_nn
bb_nn # long
bb_nn %>%
pivot_wider(names_from = name, values_from = n) # wide
### 4.4 Merging datasets and working with metadata -----
# Let's go back to our negation data. This dataset contains an entry for each linguistic expression of negation in a corpus of early 19th century Flemish soldiers' letters. Negation either occur with a 'Single' negator, or as 'Bipartite' negation (i.e. with two negators). However, there is metadata available in a separate file, linked to each of the soldiers' letters in the dataset. We want to add this to the existing data.
neg <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/negation.csv")
head(neg)
# load metadata from separate file
meta <- read.csv("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/negation_metadata.csv")
head(meta)
# compare:
head(neg)
head(meta) # look for shared identifier (here: Letter)
# merge
neg <- merge(neg, meta, by = "Letter") # first the two elements which to merge, then by="" (= the column used for merging)
# same, part of tidyverse package: left_join(), right_join(), full_join()
# check
head(neg) # success!
### 4.5 Loading multiple files (loops and lapply)-----
# loops: easy way to automate repetitive tasks
# loops have the following structure
for (i in 1:total_iterations) { # we define a counter 'i', and
# define that it will run from 1 to
# the total number of iterations
functions # functions in the loop
# will be performed i times
}
# one example
for (i in 1:50) { # define counter 'i' and iterate from 1 till 20
# function cat() (= print on screen) will run for 20 times
# with the element i in it
cat("This is iteration number", i, "\n", sep = " ") # 'cat()' is similar to 'print'
}
#### --- | exercise: multiplication tables ---#####
# Use a for-loop that will generate the result of the multiplication tables of 7 (i.e. 7x1=7, 7x2=14, 7x3=21, …, 7x50=350). First set a counter which is the number (going from 1 to 50) you use to multiply with 7, and then calculate a variable x with the result of the multiplication. Show each result for 'x' on your screen using the 'print()' function.
### ..... Loading multiple files (cont'd)-----
# loop to load various files
# as a preparation: define names of data files in a vector called data.files
data.files <- list.files(pattern="text_loop")
# any file in the working directory with " " in its name
# often you can use: pattern="txt"
data.files
# also, already created an empty data frame into which the data files will be loaded
data <- data.frame()
# start the loop
for (i in 1:length(data.files)) { # iterate over file names
# read in corpus file as lower case and save it in current.file
current.file <- read.csv(data.files[i])
# append the current.file to the rest
data <- rbind(data, current.file)
}
data
# alternative:
files <- list.files(pattern = "text_loop")
df_list <- lapply(files, read.csv)
df <- bind_rows(df_list)
df
#### --- | exercise: presidential frequency tables ---####
# Write a loop to load all (two) data files that start with the word 'freqtabel', which contains the inaugural addresses of the last two US presidents. Bind them together with 'rbind()' into one dataframe. Then use the filter() function to check how often the word 'america' occurs in each one.
#### --- | exercise: influenza ---####
# Load a collection on US age-adjusted death rates for selected major causes of death per 100,000 U.S. inhabitants (1900-2013) (source: https://data.world/health/death-rates-for-major-causes), located online ("https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/DeathRatesforMajorCauses_wide.csv"). Use the option `check.names = F` when loading the data with `read.csv` to tell R to load the year numbers as they appear (and not convert them by putting an `X` in front of them). Transform it from its current (very) wide format to a long data format. Then, filter out the death rates per year for 'Influenza and Pneumonia', and make an appropriate plot of this. Finally, make a similar plot comparing the death rates per year for all of the major causes of death in the dataset. Save the last plot as a pdf.
# Tip for plotting:
#
deathrates %>%
ggplot(aes(x = Year, y = AgeAdjustedDeathRate)) + geom_line()
# and:
# ggplot(aes(x = Year, y = AgeAdjustedDeathRate, col = LeadingCauses)) + geom_line()
#### --- | exercise: metal ---####
# Load an Excel dataset ('metal_data.xlsx') on metal bands by nation and the corresponding set of metadata ('metal_meta.xlsx') from your working directory (source: https://www.kaggle.com/mrpantherson/metal-by-nation). Use `read_excel()` from the `readxl` package. Merge the two and try to find out the following:
# - What is the name of the oldest Iranian metal band that is still together? For this last element (still together), use 'filter(is.na(split))': this will filter out the rows where the 'split' value is 'NA'.
# - Are there any Mexicans metal bands who play some sort of death metal, and if so, how large is their (total) fan base?
### 5. ANALYZING TEXTUAL DATA -----
# empty workspace
rm(list = ls(all = TRUE))
### 5.1 Loading text files -----
# texts != data files
# need to be loaded in different manner (no tabular structure)
# use scan:
# define what you want to scan (= the file),
# as what you want to load it (= character data),
# and how/where you want R to separate what you are loading
# (= e.g. each line as one element)
# per word (no specification of 'sep' needed)
corpus.file.lower.words <- scan(file = "https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/Dickens-ChristmasCarol.txt", what = character(0), quote = "")
head(corpus.file.lower.words)
# per line (sep = "\n")
corpus.file <- scan(file = "https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/Dickens-ChristmasCarol.txt", what = character(0), sep = "\n")
head(corpus.file, 100)
# alternatively:
# corpus.file <- scan(file=choose.files(), what=character(0), sep="\n")
# Windows
# corpus.file <- scan(file=file.choose(), what=character(0), sep="\n")
# Mac / Linux - library(tcltk); tk_choose.files()
# all in lower case
corpus.file.lower <- tolower(scan(file = "https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/Dickens-ChristmasCarol.txt", what = character(0), sep = "\n")) # opposite: toupper()
# encoding problems:
# corpus.file <- scan(file = "https://raw.githubusercontent.com/rikvosters/Basics-in-R/master/Dickens-ChristmasCarol.txt", what = character(0), sep = "\n", fileEncoding = "UNICODE-1-1") # argument: fileEncoding="UTF-8"
corpus.file
iconvlist() # all encoding options for platform
### 5.2 Basic text manipulation -----
# Pasting
# make vector