/
R Manual Data Management.Rmd
983 lines (824 loc) · 43.8 KB
/
R Manual Data Management.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
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
---
title: "Data Analysis Manual for R"
author: "Abu Nayeem"
date: "September 9, 2014"
output: html_document
---
##### Introduction
This Manual is meant to consolidate my knowledge in data analytics. In addition, I am happy to share data techniques and strategies to anyone. Many manuals focus on small datasets, the strategies here will try to focus on Big Data. There are different types of "big"" datasets; 1) many observations [i.e. rows], which is not too bad; 2) many columns which are more difficult as you need to assess if columns are useful or not or it is worth tinkering with. In addition, simple subsetting operations now become more tedious and time-consuming.
##### Unresolved Questions
##### Update History
MAC OS
R version 3.1.1 (2014-07-10)
R Studio version 0.98
Number of cores: 2 [Use command on terminal: system_profiler | grep -i 'Cores']
##### R markup tools
Link: [Link](http://groupware.les.inf.puc-rio.br/har)
Bold text: **bold**
Bullet point: *
* bullet
special designation: `rpart`
Italic: *Italic*
chunk commands:
```{r name}
# you can name name it
```
echo=FALSE -run but hides code great for graphs
messages=FALSE -run but does not show message of loading
warnings=FALSE - run but does not show warnings
autodep=FALSE
eval= FALSE -does not run the chunk code, still shows
results='hide' -run but does not show the output results
results='hold' -show output once all chunk written down
fig.show='hold' -hold figure output until end of code
#####1) Preparation
A) Set working directory:
A good default is create a working directory for the specifc folder. Make sure in quotes and ./ is attached to document. The code below state if not in the designated directory the create a new directory regardless of the starting point.
```{r, message=FALSE}
if (!getwd() == "./out-of-box-samples") {
dir.create("./out-of-box-samples")
setwd("./out-of-box-samples")
}
```
Suppose you want to create main directory & sub-directory for output
```{r, eval=FALSE}
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
```
B) Clear Work Space- No clutter please
```{r, message=FALSE}
rm(list = ls(all = TRUE))
date() #set date
```
C1) Install packages that may me missing on computer
```{r}
if (!library("data.table")) {
install.packages("data.table")
}
if (!library(data.table)) {
install.packages("data.table")
}
```
C2) Load Appropiate packages- Load the most important packages that you use frequently
```{r, message=FALSE}
library(plyr) # load plyr first, then dplyr
library(lubridate) # a must program in handling dates
library(dplyr) # for fancy data table manipulations and organization; Note it loads plyr as well
library(caret) # my preferred machine learning package in R; includes ggplot2
library(R.utils) # a program occasionally used to extract weird file types
library(reshape2) # for splitting column entries
library(DataCombine) # used to create lagged or forwarded varaiable
library(data.table) #useful for flexible data tablefeatures
```
D) Scripting: Prepare a script page to jot down all the steps. I recommend having it as a markdown file in R because you can shrink code chunks. Other statistical packages have their own scripting procedure. Certainly don't use a text file.
E) Data Dictionary: For raw data and supplementary analyzes, a data/coding dictionary is crucial in making the dataset both understandable and accessible to other users. KNOW the size of the data and if your computer can handle opening it up
F) Optimizing Code/ Debugging : For big datasets, we want the code to run as fast as possible but still be readable; R by default only uses a single core when operating, you need to get access to new libraries to use multiple cores. Finally parallel processing allows access to use multiple cores
```{r, message=FALSE}
system.time(names(mtcars)) # gives some values of the time it takes to execute an action; Note you can take a huge chunk of code as well
summaryRprof() # gives time slots where most of the computing going to, its helpful for long functions
print(object.size(x), units = "auto") #memory use for any particular object
```
Debuging Example
```{r}
fun1 <- function(x) {
x <- x * 2
fun2(x)
}
fun2 <- function(x) {
fun3(x)
}
fun3 <- function(x) {
apply(x, 1, mean)
}
```
1) We can use ``debug()`` to step through a function line by line
2) After an error occurs, we can use ``traceback()`` to look at the *call stack*
3) More helpfully, if we set ``options(error = recover)`` before running code, we can go into the function in which the error occurred
4) We can insert ``browser()`` inside a function and R will stop there and allow us to proceed with debugging statements
5) You can temporarily insert code into a function (including built-in functions) with ``trace(fxnName, edit = TRUE)``
G) Constructing your own functions: Unless you are in the cutting edge or face redundant operations or handle similar datasets, then it worth the time to write. R package functions provide greater protection against faulty code
H) General Stylized Rules:
Google R Stylized Rules: http://google-styleguide.googlecode.com/svn/trunk/Rguide.xml
Unit Testing Rules for functions: http://master.bioconductor.org/developers/how-to/unitTesting-guidelines/
Git Setup: file://localhost/Users/abunayeem/Desktop/R%20Directory/paciorek-r-bootcamp-2013%20(1)/modules/module9_workflows.html
For R as a programming language [it is recommended python handle it]: file://localhost/Users/abunayeem/Desktop/R%20Directory/paciorek-r-bootcamp-2013%20(1)/modules/module10_advanced.html
###2) Extracting Data
A) Pre-Research:
Know what data and/or question you are interested in. This is particulatly important when datasets are absolutely massive
B) Extraction:
You want your code be able to replicated anywhere either fixed file on library or the alternative online access [github repository]. There are numerous extraction options. It is helpful to use the Rstudio interactive feature of importing data to see a subset of the data, which can inform you of the dividers, missing variable, missing a column or not Note: By giving data.table more info in advance you reduce computing time.
```{r, message=FALSE}
url <- "XXXXXhttps://d396qusza40orc.cloudfront.net/repdata%2Fdata%2FStormData.csv.bz2"
download.file(url, "repdata-data-StormData.csv.bz2", method="curl")
#"curl" is needed for mac
bunzip2("repdata-data-StormData.csv.bz2",dest="repdata-data-StormData.csv", overwrite=TRUE, exdir="./Repository Important")
#Set location (exdir) to working directory
portion<-file("repdata-data-StormData.csv","r")
#make it to readable file for extraction, so we can extract certain elements; useful for big files
StormData<-read.csv(text = grep("^[1,2]/2/2007",readLines(portion),value=TRUE), header=FALSE, sep=",", comment.char="")
#we are looking for the text that match and extract those rows. This works for time, another way is take explicit number of rows;
#other features include skip, nrows, stringsAsFactors, na.strings,and ColClasses, the last item is to store the data with less RAM
colnames(Power)<-t(Columns[1])
#the transposed matrix of one is appeneded to primary dataset as column names
```
Extraction of zip with multiple files:
```{r}
temp <- tempfile()
download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip ",temp)
unzip(temp, list = TRUE) # This shows the list of files name!
YTest <- read.table(unzip(temp, "UCI HAR Dataset/test/y_test.txt"))
unlink(temp)
```
SQL Method: Extraction
```{r, message=FALSE}
library('sqldf')
file <- "household_power_consumption.txt"
dates <- "SELECT * from file WHERE Date = '1/2/2007' OR Date = '2/2/2007'"
# getting the records from the file filtering with the SQL sentences
data <- read.csv.sql(file, sql=dates, sep=";")
```
Strategy: Take a small sample and the figure out the classes of the columns and repsond accordingly
```{r, message=FALSE}
file<-"household_power_consumption.txt"
a<-read.table(file,nrows=10) # create a smaller subset of data
classes<-sapply(a,class) # separate the classes
b<-read.table(file, colClasses=classes) #now classes are given much more in advance
read.table(file, colClasses=c("character","character",rep("numeric",times=7))) # if you know the class of the tables then this is better
```
Loading previous workspace: `source(data.R)`
### Data Cleaning/ Presentation
Assume you were given raw data. How do you clean the data to make it more accessible?
A) What is the task given to you? Depending on the question you want to answer you may only clean a small portion of the entire dataset. However, to redo analysis with same raw dataset, we need to reclean once again. Thus a global cleaning process is recommended. However, computing power may be limited and priorities may be placed elsewhere.
B) Basic Overview
```{r, message=FALSE}
Cars<- tbl_df(mtcars) #this type of dataframe computationally faster and accessible
str(Cars) # show columns associated class
names(Cars) #column names
summary(Cars) # get a feel if there is missing data
dim(Cars)# the dimensions of your data
CC<-Cars[1:3,] ;CC$A<-c("Tom","DOG","poop") ;CC$B<-c("ToM","DOG","PoOp") # easy dataframe to work with
table(CC$A) #this gives quick frequency of a variable
head(CC); tail(CC)
```
C) Handling Time
Lubridate [Convert character to date variable]
```{r, message=FALSE}
library(Lubridate)
ymd("1989-05-17") #it is very smart and maneurable in handling dates as order don't matter!
```
Convert Date and Time together
```{r, message=FALSE}
DateTime <-paste(X$Date,X$Time)
X$DateTime <-strptime(DateTime, "%d/%m/%Y %H:%M:%S")
```
Find day of the week
```{r, message=FALSE}
weekdays(FullActivity$date) # it takes the date and use an internal calendar to figure out what day of the week it is
```
D) Removing Duplicate or Weird Observations
Removal of duplicate columns :
```{r, message=FALSE}
CC[, !duplicated(colnames(CC))] #[Assumed they have same values in entries]
```
For Character Entries:
The criteria of removal should follow some guidelines
1) When there is no unique ID, then a identical datapoint can be valid. An index can help to show a unique observation rather than an error
2) If a primary ID exists do the following, prior to hitting unique
```{r, message=FALSE}
duplicated(CC) # this highlights which variables are completely identical
a<- duplicated(CC, by=key(ID)) # spot unique data by the unique only rather than all the variables
CC[a,] #make sure you compare the variables and see any anomalies
CC[-a,] #I recommend choosing which of the identical data is worth removing
```
3) For Numerical Entries [same methods as above] :
Use the summary feature, to spot any oddities on the numeric vectors which include unreasonable outliers and contradictory values such as negative values [example: price]
```{r, message=FALSE}
summary(CC)
select(CC, wt>0, mpg<20) # this subsetting remove observations from the dataset, so be wary what you remove
```
E) Converting Classes: Classes should be changed early upon extraction but if not we can do the following
Example: the number of cylinders (cyl) in mtcars data may be better suited as a factor since the number of cylinders is discrete.
```{r, message=FALSE}
CC$Cyl<- as.character(CC$Cyl) # convert integer to character; do your manipulation with entries
CC$Cyl<- as.factor(CC$Cyl) # convert character to factor, notice the summary feature provides useful information
CC$Cyl<- as.numeric(CC$Cyl) # factor to integer, the circle of class is complete
```
Suppose we face the issue that the orginal factor variables are number strings. You need to be really careful in converting it to numeric
```{r}
CC[, 1] <- round(as.numeric(as.character(CC[, 1])), 3) # this works for both factors, but also notice I used the round function which makes it more pleasant to see data
```
Note:
1) When creating mixed vectors, R chooses the lowest value of the vectors (i.e. character) to determine the class; also take note of list and vector class. This is important especially if introducing a string entry to a numeric column
2) Watch out for missing values when cconverting classes
3) For some factor variables may be ordered, so assign it when converting as shown below:
4) Factor variables can serve as dummy varaibles
```{r, message=FALSE}
CC$A<- as.character(CC$A) # convert integer to character; do your manipulation with entries
CC$C<- factor(CC$A) # this creates new variable but the default level is based alphabethic
CC$D<- as.factor(CC$A, levels=c("poop", "dog"))# the new variable is now ordered with poop at highest level
```
F) Upper and lower Case of strings. This is useful if implementing string manipulation
Column Names: we want lowercase all the letters and then capitalize it with a function
```{r, message=FALSE}
names(CC)<- tolower(names(CC)) #lower case all strings on columns
capFirst <- function(s) {
paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "")}
# this function takes a string and capitalize only the first letter
names(CC)<-capFirst(names(CC)) # Implement Capitalization Function
```
Single Row Entries:
```{r, message=FALSE}
CC$A<- tolower(CC$A) # lower case all strings in the column
CC$A<-capFirst(CC$A) # capitalize function works in this case too
```
Multiple Row Entries: converting one column variable at a time is tedious. The code checks multiple columns and then lower case them accordingly.
```{r, message=FALSE}
CC<-data.frame(lapply(CC, function(v) {
if (is.character(v)) return(tolower(v))
else return(v)
}))
```
#I have not figured a good way to capitalize all variables at once, though probably not that useful
Removing empty space in column names: When calling on column IDs the empty space can cause problems not only in R but in other languages and functions.
```{r, message=FALSE}
names(CC)<-gsub("","_",names(CC))
```
G) Handling Missing Values [Make sure you find what previous text file described missing values while importing data]. Data that does not comply should become missing data. Remember missing data can be ignored in certain cases. We may want to keep missing data if they hold some importance or could be filled in later
Spotting:
```{r}
CC$test<-c(2,5,NA)
CC$dumm<-c(3,4,5)
colSums(is.na(CC))>0 #checks if each column has missing values
```
Case 1: We have a lot of incorrect entries in a column, instead of handling each entry separately. We can treat each incorrect entry as missing value
```{r, message=FALSE}
a<-grep("[^t]",CC$B,value=FALSE) # find row index that does have those strings
CC[a,13]<-NA #we then set those values NA
```
Case 2: Suppose we want to get rid of NA entries based from a specific column.
```{r, message=FALSE}
filter(CC,!is.na(B)) # keeps non-NA entries based on that column
```
Case 3: Suppose you want to get rid of NA entries in all columns
```{r, message=FALSE}
good<-complete.cases(CC) # looks in entire dataframe for missing values
CC[good,] # the subset leaves only entries that has no missing values at all
```
Case 4: Suppose we want to get rid of columns with missing values
```{r}
library(data.table)
CC <- as.data.table(CC)
CC[,which(unlist(lapply(CC, function(x)!all(is.na(x))))),with=F] # this gets rid of ALL columns with ONLY NA values
a<- which(colSums(is.na(CC)) > 0) # the WHICH function creates a numerical index for the logical test
CC[,-a] #notice there is a negative sign which is to remove the columns that had spotted NA values
```
NOTE: the which method is needed for logical vectors involving column index, but row index can take logical vectors fine
Note: NaN is missing integers and NA change class type; NaN and NA are Not the same
H) How to shift columns around/ and extract row names. Note: We want the unique ID to be at leftmost.
```{r, message=FALSE}
select(CC,3,2,1,ncol(CC):4) # I rearranged the first three columns, and kept the remainder the same, but backward order; Note: this is actually subset, so make sure all cols are still there
CC$names <- rownames(CC) # this extracts the row names
rownames(CC)<-NULL # this deletes the row name. Make sure to extract first.
```
I) Sorting within dataset
```{r, message=FALSE}
arrange(mtcars, drat,desc(q)) # double layer sorting where intial value is ascending and upon that it is descending; Application is useful for multi-level lagged variables
```
J) Sometimes it is useful to create an index, but make sure to sort beforehand if intention to do something
```{r, message=FALSE}
CC<- arrange(CC,Wt) #arrange data frame
CC$Index <-seq(along=nrow(CC)) #create a sequence of values based on # of rows, so it picks up missing values as well
```
K) Rounding Numbers: It makes it much pleasant looking
```{r}
round(Cars$drat, 1) # a single column
Cars[, c(5,6)]<- round(Cars[, c(5,6)], 1) # multiple columns and subsetts
```
### Data Manipulation
A) Meticulous Data-Mining:
The column names are easy to check if in proper order, but the entries can be jumble mess.
1st level: For essentially all variables you check if the values are correctly specified
For mispelling of character entries: Use gsub or grep to fix
```{r, message=FALSE}
list(unique(CC$A)) # this shows the unique values and you can spot which ones need to be changed; Use grep
```
For spotting weird numeric entries:
```{r, message=FALSE}
summary(CC$wt) # check if max or min fit desired criteria [no missing values or negative numbers]
all(data$val>0) # check if there is any negative values on the dataset, it gives only one statement
```
For finding out frequency of values of strings [place into a factor first]
```{r, message=FALSE}
CC$A<- as.factor(CC$A) # change character vector to a factor
summary(CC$A) #Now we view the frequency of each factor variable
table(Cars$Cyl, useNA="ifany") # General form of looking frequency and adds a column if there is any NA
```
2nd Level: When you believe certain pairs of columns (factors) should be matched together.
For example: A teacher (teacher) should be assigned to a several specific classrooms (class)
```{r, message=FALSE}
table(CC$teacher, CC$class) # this creates a cross-sectional frequency table; Note any unusual pairings
```
3rd Level: This is higher level matching and there is probably a sleek function to test it all at once. Most of the time, the 2nd level data cleaning will catch most of the proper matches.
B) Subsetting and filtering
Columns:
```{r, message=FALSE}
mtcars[,c(3,4,5,7)] # standard subsetting method
mtcars[,3]; mtcars[3] # this is WRONG.
select(mtcars,3:5,7) # I only took cols 3 to 5 and 7
#select features also include other arguments like start_with(); ends_with(),contains(),match(),num_range()
select(mtcars,starts_with("d"), more argument) #choose the columns that only start with d
select(mtcars,-starts_with("d")) #choose the columns that not start with d WITH the minus sign
select(mtcars, contains("t")) # looks for columns that has t
```
Column Subsetting with grep index strategy
```{r, message=FALSE}
a<-grep("^d",names(mtcars),value=FALSE); mtcars[,a]; select(mtcars,a) # grep function allow to choose string, we use that index vector (value=FALSE) to subset
grep("^d",names(mtcars),value=TRUE) # this shows the list of names where there is a match
a<- names(mtcars)>"g" #also creates an index but more limiting
```
Rows:
```{r, message=FALSE}
mtcars[c(2,5,6),] # the standard format of taking three rows
filter(mtcars,drat>3.10, qsec>17) #filter on two conditions solved simultaneously!
filter(mtcars,drat>3.10 | qsec>17) #two conditions with an OR aspect
filter(CC, colA>"g") # you can filter by strings and there is greater than and less than respect to alphabet on FIRST character only
filter((CC, colA>"oo")) # it test the first letter if satisfied as a tie than to second line from first character
a<-grep("oo",CC$A,value=FALSE); CC[a,] # for greater precision [i.e exact matches of strings] you can use grep strategy again
a<-mtcars$wt>2.5 & mtcars$hp>100 # this creates a logical index similar to grep function, but we can use multiple arguments
```
Rows & Columns: Protip you can combine grep function indexes (or any indexes) at the same time
```{r, message=FALSE}
mtcars[1,5] # the entry value from first row and 5th column; class is a number
mtcars[c(1,10),c(5,6)] # return a data.frame with first row and 5th and 6th column
mtcars[a,b] #each variabe is an index to subset data by columns and rows but they satisfied some condition
```
Lists:
```{r, message=FALSE}
x[[2]] # returns the elements of a list, rather than the list item itself
```
C) Adding new Data; Note r handles merging a lot better than most statistical software
Columns:
```{r, message=FALSE}
mutate(mtcars,A=1:32,am_gear=(am*gear)/2) # first column A correspond to any vector; am_gear represents an operation to create new column
```
Adding lagged/leading columns:
```{r, message=FALSE}
a<- slide(CC,Var="A",slideBy=-1, NewVar="lag1wt") # uniform lag 1
a<- slide(LagDaySteps,Var="A",slideBy=1, NewVar="lead1wt") # uniform lead 1
Grouplag<-arrange(Grouplag, cyl) # when doing a first layer lag you need to sort
slide(Grouplag,Var="wt",slideBy=-1, GroupVar="cyl", NewVar="lag1wt") # lagged 1 by cyl by group;
```
Rows: A cumbersome ordeal since the row vector need to have same number of rows as the data frame
Row merging:
```{r, message=FALSE}
rbind(mtcars,Cars) # number of columns AND column names need to be the same, though order of columns don't matter; Note in many loops rbind is used frequently to build up observations from an empty matrix
```
Column merging:
```{r, message=FALSE}
cbind(mtcars,Cars) # number of rows need to be same not to intersting
```
Data.frame merging: No doubt the most crucial merging- we merge on basis of a common ID. [ORDER don't matter]
Case 1: Unique Merging- this is the case where there is unique ID for both datasets
```{r, message=FALSE}
merge(mtcars,Cars,by="ID") # since the IDs are unique, the merged matrix consist of only EXACT matches
```
Case 2: Unique Merging with keeping non-matched data [i.e. unmatched ID]
```{r, message=FALSE}
merge(mtcars,Cars,by=c("ID","blue"),all.x=TRUE,all.y=TRUE) # IDs can be multipe arguement, but notice the additional values are meant to not throw out unmatched pairs. Many of the values will become NA
```
Case 3: Non-Unique Merging: Suppose matrix A has unique ID where matrix B has some duplicate ID but with different values
```{r}
A<-data.frame(id=1:5,b=6:10)
B<-data.frame(id=c(1,1,2,2,3,3,4,4,6,6),c=1:10) #note it has multiple ids
merge(B,A,by="id") # shows all unique combinations of the id
merge(B,A,by="id",all=TRUE) # include ALL IDs that did not match
```
D) Splitting Existing Columns: when there is excess information in one column
```{r, message=FALSE}
df <- data.frame(country =c("Angola","Belize"),dates = c("1951-1953", "1970-1972")) # Our goal is want to separate the years from start date to end date and place value
df <- cbind(df, colsplit(df$dates, "-", c("start", "end"))) # we take column and split it with "-" for two variables; to get a sequence
#split sequence
ddply(df, .(country), function(x){
data.frame(
country=x$country,
yrobs=seq(x$start, x$end),
yrstart=x$start,
yrend=x$end
)
}
)
df
```
E) Replacing variables and strings
Column Names:
```{r, message=FALSE}
names(CC)<-gsub("q","Quarter", names(CC)); # it finds matching string and replace with that string ; useful shortening names or expanding column names; NOTE this an easier way to change a col
names(CC[7])<-"Quarter"
```
Row Entries: we can use the index strategy once again
```{r, message=FALSE}
Cars$Disp[Cars$Drat<3] <- 0 # we change the value in the discipline entry if certain condition satisfied
a<-Cars$Drat<3 | blah ; Cars$Disp[a]<-0 # index method can work which means grep can work too
```
F) Grouping and Collpasing Datasets: Grouping is convenient when we want to keep the dataset pristine and able to aggregate values. Rules for collapsing data: 1) Figure out the primary new ID/factor 2) Perform all the duties because you CANNOT go backward
Case 1: Grouping upon a factor/group to find mean across groups; Don't use dcast function, it's not too great
```{r, message=FALSE}
CCGroup<-group_by(CC,Cyl) # we create a new function which automatically register Cyl as the "group"
summarize(CCGroup, mean(Wt),sum(Qsec)) # this takes the mean and sum calculations and displays it by group basis
```
Case 2: Grouping by more than one layer; also collapsing dataset [always arrange appropiately and watch out for missing]
```{r, message=FALSE}
ddply(CC,.(Cyl,Carb),summarise,Aver=mean(Drat)) # it groups cycle and Carb and takes the mean of Drat for each subcategory
# More quick ay doing it but you are limited to one operation
outData<-aggregate(selectedData,by=list(Activity,Subject),FUN=mean,na.rm=TRUE)
#another way to do above
Master.dt[,lapply(.SD, mean),by='participants,activities'] #This takes the mean of EVERY column broken down by participants and activities; Great for big data but not useful for data analytics
# Another way to sum up values respect to a group
xtabs(drat~cyl,mtcars)
```
Saving new table externally in some sort of text file:
```{r, message=FALSE}
write.table(TidyData,file="Tidy.txt", row.names=FALSE)
```
G) Handling Missing values: Remember the feature "na.rm=TRUE" exists for many functions!
```{r, message=FALSE}
colSums(is.na(data))
```
H) Loops and Advanced: Avoid if necessary
Loop Example: MAKE sure it is (i in [SEQUENCE]), a good range is 1:length(unique(CC$Hp))
```{r, message=FALSE}
x=c("a","b","c")
for (i in seq_along(x)) {print(x[i])} # this automatically fits to the length of the vector
```
WHILE using a random walk example: the code simply states if the draws reach 3 or 10 this code stop running
```{r, message=FALSE}
z<-5
while(z>= 3 && z<=10) {
print(z)
coin<-rbinom(1,1,0.5)
if (coin==1) {
z<- z+1
} else {
z<- z -1
}
}
```
Repeat: creates an infinite loop until you use break to stop it, it is good when using tests for convergence, but we never know if it will converge or not. Other features inlcude next which skips iterations
```{r, message=FALSE}
repeat {
x1<- computeEstimate()
if (abs(x1-x) <tol) { break
} else {
x<-x1
}}
```
I) Functions: Avoid unless necessary or redundant work
Sample Function: Good base example of a function that updates. Another approach is to continually append the vector for each loop. If we were trying to get a data.frame of observations than very likely we would use rbind.
```{r, message=FALSE}
colmean <- function(y, removeNA= TRUE) { # removeNA has a default value and y is a matrix
nc<- ncol(y) #nc is the number of cols in matrix y
Means <-numeric(nc) # empty vector of size of number of rows
for (i in 1:nc) { # the loop will be going through every column
Means[i]<- mean(y,[,i], na.rm=removeNA) #it will take the mean of a column and store it under the varaible Means
}
Means # it returns the final product with all means
}
```
Lexical Scoping in R: The difference between lexical vs dynamic scoping is that the global variable is resticted to parent environment under the lexical scoping
Example of a DOUBLE layer nested function ; use cautiously. Where each layer needs to be defined if to be used
```{r, message=FALSE}
make.power<- function(n) {
pow<- function(x) {
x^(n)
} pow
}
quad<- make.power(4) # first you need to determine the value of exponent n
quad(8) #second you put a place value
```
Using lapply (challenging to use), sapply (useful), tapply (restrictive, plyr package better), split (pylr package better)
```{r, message=FALSE}
lapply(CC, mean) # treat the data frame as a list and implment action on each column
sapply(CC[a,], mean) ### same as lapply but puts out on vector. This a quick way of getting column means of every variable and with with index you can restrict rows/columns accordingly
apply(CC[,c(1:11)],2,mean) # these function cannot handle string variables, also two means that columns are kept
apply(CC[,c(1:11)],1,quantile, p=c(0.25,0.75)) # now rows are kept and columns are collapsed, in addition I created a quantile ; for sums and means there are quicker function calls rowMeans (etc),
tapply(CC,A,mean) # for tapply to be used the number of factor observations is identical [USE ddplyr instead]
tapply(CC$Mpg,CC$Hp, mean) # both variables are of same length so it can work
split(CC,Cyl) # creates a list of dataset broken down by factors A
split(CC,list(Carb,Cyl),drop=TRUE) # creates a sublist similiar to dplyr, but try every COMBINATION; drop equal to true is to remove empty combinations
lapply(split(CC,Cyl),mean) # does not handle dataframes too well, so use dplyr
```
J) Useful functions [Not Useful- Cross tabs]
Sequence:
```{r}
seq(1,10, by=3) # 1-10 increase by 2 ; counts by three starting from 1
seq(1,10, length=6) # it now takes this range and splits it perfectly evenly
quantile(tree$LFBM)
```
Literal Commands [GREP]:
```{r}
literal # exact matches
^i think # specify the beginning of sentence
morning$ # specify the ending of sentence
[Bb][Uu][Ss][Hh] # capitalization does not matter
^[Ii] am # combined the two
^[0-9][a-zA-Z] # sentence begin with number and word
[^?.]$ # when symbol inside it says if not ? or period at end then show
9.11 # the dot represents any character
flood| fire | coldfire # it's an alternative [i.e. or]
^[Gg]ood | bad # only good is restricted to beginning of line
^(good|bad) # transitive property
Hey ( [Ww]\.)? # the question mark indicates it is optional
(.*) # looking for parenthesis, not concerned about anything
# you can differentiate the number of words apart
# you can find repetitions of a phrase in a sentence
```
Unique Indices: For extractions in code
```{r}
unique(CC$Wt)[1] # the output showed the unique value (I presume alphabetically)
```
### Presentations and basic plot displays
A) Plotting: the three major packages is base plot, lattice, and ggplot (favorite); Exporting the plots in different formats do matter so be aware and remember to close the screen browser after savinf a photo. JPEG and PNG (poor resize); pdf (good at resizing)
Base Plotting:
```{r, message=FALSE}
par(mfrow=c(2,2)) # for the graphics windows we create two rows and two columns [i.e. 4 graphs will exist on same graphics device ]
with(Power,{ #the curly brackets enable multiple plots to be implemented at ease as long base data being used
plot(DateTime, Global_active_power, type="l", ylab="Global Active Power") # Plot 1; type l represent use line graph
plot(DateTime, Voltage, type="l") # Plot 2
plot(DateTime,Sub_metering_1, type="l", ylab="Energy Sub Metering",col="grey") #Plot 3; this will have multiple plot on same table
points(Power$DateTime,Power$Sub_metering_2, type="l",col="red") # within plot 3 but with different datapoints
points(Power$DateTime,Power$Sub_metering_3, type="l",col="blue")
legend("topright",lty=1,bty="n",cex=0.4, col=c("grey","red","blue"),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) # legend where cex determine text size ; lty determine the shape of symbol
plot(DateTime, Global_reactive_power, type="l")
})
dev.copy(png,filename="plot4.png") # this saves the plot image to an external file
dev.off() #MAKE SURE you close this browser
```
Qplot: The most simplest plotting package in ggplot2 package
```{r, message=FALSE}
#Plot 1
by_Event_StormData <- arrange(by_Event_StormData, desc(TotMPropDmg)) # arrange the data
qplot(TotMCropDmg,TotMPropDmg,data=by_Event_StormData[c(1:10),], col=Event, xlab="Total Crop Damage ($Million)",ylab="Total Property Damage ($Million)", main="Most Harmful Events to Economy") # notice I used the index to pick certain data; the default in qplot of two variables is scatterplot; col=Event colors my data respect to associated Event. See the first R-pub document
#Plot 2
qplot(date,TotSteps,data=TotalDay, geom="histogram", stat="identity",main="Total Steps Vs Time With NA Values", ylab="Total Steps")
# the geom is crucial in determining what kind of plot you want to produce. see help or online to see all feature available
qplot(drat, wt, data=mtcars, facets ="cyl~.") # three plots in row spearated by cyl
qplot(drat, wt, data=mtcars, facets =".~cyl") # three plots in column separated by cyl
```
GGPlot:
```{r}
ggplot(data = , aes(x = , y = , color = , linetype = , shape = , size = ))
plot1 = ggplot(data = mydata.subset, aes(x = year, y = vturn, color = )) + geom_line(aes(color = country))
plot2 = ggplot(data = mydata.subset, aes(x = year, y = vturn, linetype = )) +
geom_line(aes(linetype = country))
plot3 = ggplot(data = mydata.subset, aes(x = year, y = vturn, shape = )) + geom_point(aes(shape = country))
grid.arrange(plot1, plot2, plot3, nrow = 3, ncol = 1)
ggsave(filename = , plot = , scale = , width = , height = )
```
Saving Plots quick code:
```{r}
dev.copy(png, "Blah.png", height = 480, width = 480)
dev.off()
```
B) Tables are extremely useful but we do not want to rely on Excel all the time
Basic Table: [I take advantage tbl_df]
```{r, message=FALSE}
CC<-tbl_df(CC) #transform to a special dataframe
CC %>% arrange(desc(Wt)) %>% select(1,2,5,6) # this one of numerous ways to create a table, notice there is chaining involved %>%
```
Advanced Table: TBA
### Advanced: Tidy Data Set: Three Rules;
1) Each variable forms a column
Violation: suppose there is two columns to represent gender
2) Each observation forms a row
Violation: suppose there is two IDs that share many things except one column attribute and thus separate
3) Each type of observational unit forms a table
More complex and structural based
A) Problem 1: you have column headers that are values
grade male female
1 A 1 5
2 B 5 0
3 C 5 2
4 D 5 5
5 E 7 4
Issue: Gender count is in two columns, which is easy to view, but you won't be able to do linear regression well or factor analysis
Solution: Gender should be in one column, and count on the other column
```{r}
gather(students,sex,count,-grade) # this creates two columns sex and count; it breaks down previous male and female columns into single column varaible; Note the minus sign before grade, which says we want to gather all columns EXCEPT grade
melt(data, id="grade") #this essentially does gather but doesn't allow naming, so you need to name separately; MELT can specify which variables you want to keep and which ones to gather, you can also remove which data is not useful and implement gather
```
grade sex count
1 A male 1
2 B male 5
3 C male 5
4 D male 5
5 E male 7
6 A female 5
7 B female 0
8 C female 2
9 D female 5
10 E female 4
B) Problem 2: column headers that are dual value
grade male_1 female_1 male_2 female_2
1 A 3 4 3 4
2 B 6 4 3 5
3 C 7 4 3 8
4 D 4 0 8 1
5 E 1 1 2 7
Issue: Gender Count AND Class is on the column variables
Solution: we want separate sex and count into separate variables
```{r}
res<-gather(students2,sex_class,count,-grade)
# we create two columns, where sex_class will have four factors related gender and class and each respective entry is in count
melt(data, id="grade") # same as above
separate(res,sex_class,c("sex","class"))
# we separate sex_class into sex and class. This operator is smart enough to see "_" exist in both column and entries or you set the separator
```
grade sex class count
1 A male 1 3
2 B male 1 6
3 C male 1 7
4 D male 1 4
5 E male 1 1
6 A female 1 4
7 B female 1 4
8 C female 1 4
9 D female 1 0
10 E female 1 1
11 A male 2 3
12 B male 2 3
13 C male 2 3
14 D male 2 8
15 E male 2 2
16 A female 2 4
17 B female 2 5
18 C female 2 8
19 D female 2 1
20 E female 2 7
C) Problem 3: when variables are stored in both rows and columns
name test class1 class2 class3 class4 class5
1 Sally midterm A <NA> B <NA> <NA>
2 Sally final C <NA> C <NA> <NA>
3 Jeff midterm <NA> D <NA> A <NA>
4 Jeff final <NA> E <NA> C <NA>
5 Roger midterm <NA> C <NA> <NA> B
6 Roger final <NA> A <NA> <NA> A
7 Karen midterm <NA> <NA> C A <NA>
8 Karen final <NA> <NA> C A <NA>
9 Brian midterm B <NA> <NA> <NA> A
10 Brian final B <NA> <NA> <NA> C
Issues: 1) all these missing values, obviously it would be better to create a class variable; 2) the final and midterm grade gives information on two classes
Solution: You may be tempted to put each student on one line that would entail two class variable. The goal is to get as much information of a single class for a single student
```{r}
dat<-gather(dat,class, grade, class1:class5, na.rm = TRUE)
#OR
dat<-gather(dat, class,grade,-(name : test),na.rm = TRUE)
#create new cols class and grade which we mush colnames; na.rm=TRUE makes sure we ignore missing values; NOTE: test and name is not touched
dat<-spread(dat,test,grade)
# it takes test and seprate it into two columns and put corresponding grades; NOTE this is opposite to gather!
mutate(dat, class= extract_numeric(class))
# the final step replace class entries with ONLY the numeric values which determine the class number
```
name class final midterm
1 Brian 1 B B
2 Brian 5 C A
3 Jeff 2 E D
4 Jeff 4 C A
5 Karen 3 C C
6 Karen 4 A A
7 Roger 2 A C
8 Roger 5 A B
9 Sally 1 C A
10 Sally 3 C B
D) Problem 4: multiple observational units are stored in the same table
id name sex class midterm final
1 168 Brian F 1 B B
2 168 Brian F 5 A C
3 588 Sally M 1 A C
4 588 Sally M 3 B C
5 710 Jeff M 2 D E
6 710 Jeff M 4 A C
7 731 Roger F 2 C A
8 731 Roger F 5 B A
9 908 Karen M 3 C C
10 908 Karen M 4 A A
Issues: There is simply too duplicity where the first three columns combination are unique per ID. The issue is that it may take up a lot of space to each variable when it doesn't provide much insight
Solution: To save database/memory, we put identical characteristics of primary ID into one data.frame while the more dynamic charactersitics on another data frame. For example: Notice that many data libraries have two main dataframes; 1) One is performance with different observations etc., and the other is description of the "primary ID", which can be hospitals, banks, etc.
Step 1: Save the primary ID characteristics [Used chaining (reduce amount of calling) this time around]
```{r}
student_info <- dat %>%
select(id, name, sex) %>% #find the matched charactersitics
unique() %>% #keep only uniqued values [i.e. remove duplicates]
```
id name sex
1 168 Brian F
3 588 Sally M
5 710 Jeff M
7 731 Roger F
9 908 Karen M
Step 2: Save the dynamic charactertics, but make sure you still keep at least one primary ID variable
```{r}
gradebook <- dat %>%
select(id,class,midterm,final)
```
id class midterm final
1 168 1 B B
2 168 5 A C
3 588 1 A C
4 588 3 B C
5 710 2 D E
6 710 4 A C
7 731 2 C A
8 731 5 B A
9 908 3 C C
10 908 4 A A
E) Problem 5: when a single observational unit is stored in multiple tables
> passed
name class final
1 Brian 1 B
2 Roger 2 A
3 Roger 5 A
4 Karen 4 A
> failed
name class final
1 Brian 5 C
2 Sally 1 C
3 Sally 3 C
4 Jeff 2 E
5 Jeff 4 C
6 Karen 3 C
Issue: These two separate dataframes is not needed one table can explain all the information needed.
Solution: We simply create a new column that state passed or failed
```{r}
passed<- passed %>% mutate(status = "passed") # create new col for each data frame
failed<- failed %>% mutate(status = "failed")
rbind_list(passed,failed) # combine the datasets by stacking observations
```
name class final status
1 Brian 1 B passed
2 Roger 2 A passed
3 Roger 5 A passed
4 Karen 4 A passed
5 Brian 5 C failed
6 Sally 1 C failed
7 Sally 3 C failed
8 Jeff 2 E failed
9 Jeff 4 C failed
10 Karen 3 C failed
F) Problem 6: Suppose you had this mess of a dataset where there is many arguements that need to be tidy up. NOTE: the data belows show the count of individuals in that range
score_range read_male read_fem read_total math_male math_fem math_total
1 700???800 40151 38898 79049 74461 46040 120501
2 600-690 121950 126084 248034 162564 133954 296518
3 500-590 227141 259553 486694 233141 257678 490819
4 400-490 242554 296793 539347 204670 288696 493366
5 300-390 113568 133473 247041 82468 131025 213493
6 200-290 30728 29154 59882 18788 26562 45350
Variables not shown: write_male (int), write_fem (int), write_total (int)
Issues: 1) Separate male and female; 2) Separate reading, math, writing; 3) how to handle total values
Solution: Use the gather strategy to separate the sex, part, count. In addition, you need to
```{r}
sat %>%
select(-contains("total")) %>% #remove total variables because they are just simply operations
gather(part_sex, count, -score_range) %>% # keep score range- this should create extensive column list
separate(part_sex, c("part", "sex")) %>% # separate part and sex together
group_by(part,sex) %>% #its simply not re-ordering, but it allows some group function to be implemented
mutate(total= sum(count), # create new variables like sum which count part and gender
prop= count/total # variable for gender proportion at this range
) %>%
```
score_range part sex count total prop
1 700???800 read male 40151 776092 0.05173485
2 600-690 read male 121950 776092 0.15713343
3 500-590 read male 227141 776092 0.29267278
4 400-490 read male 242554 776092 0.31253253
5 300-390 read male 113568 776092 0.14633317
6 200-290 read male 30728 776092 0.03959324
7 700???800 read fem 38898 883955 0.04400450
8 600-690 read fem 126084 883955 0.14263622
9 500-590 read fem 259553 883955 0.29362694
10 400-490 read fem 296793 883955 0.33575578
11 300-390 read fem 133473 883955 0.15099524
12 200-290 read fem 29154 883955 0.03298132
13 700???800 math male 74461 776092 0.09594352
14 600-690 math male 162564 776092 0.20946486
15 500-590 math male 233141 776092 0.30040382
16 400-490 math male 204670 776092 0.26371873
17 300-390 math male 82468 776092 0.10626060
18 200-290 math male 18788 776092 0.02420847
19 700???800 math fem 46040 883955 0.05208410
20 600-690 math fem 133954 883955 0.15153939
21 500-590 math fem 257678 883955 0.29150579
22 400-490 math fem 288696 883955 0.32659581
23 300-390 math fem 131025 883955 0.14822587
24 200-290 math fem 26562 883955 0.03004904
25 700???800 write male 31574 776092 0.04068332
26 600-690 write male 100963 776092 0.13009154
27 500-590 write male 202326 776092 0.26069847
28 400-490 write male 262623 776092 0.33839158
29 300-390 write male 146106 776092 0.18825861
30 200-290 write male 32500 776092 0.04187648
31 700???800 write fem 39101 883955 0.04423415
32 600-690 write fem 125368 883955 0.14182622
33 500-590 write fem 247239 883955 0.27969636
34 400-490 write fem 302933 883955 0.34270183
35 300-390 write fem 144381 883955 0.16333524
36 200-290 write fem 24933 883955 0.02820619