R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run R
commands within a LaTeX document.
1# Comments start with hash signs, also known as number symbols (#).
2
3# You can't make multi-line comments,
4# but you can stack multiple comments like so.
5
6# in Windows you can use CTRL-ENTER to execute a line.
7# on Mac it is COMMAND-ENTER
8
9
10
11#############################################################################
12# Stuff you can do without understanding anything about programming
13#############################################################################
14
15# In this section, we show off some of the cool stuff you can do in
16# R without understanding anything about programming. Do not worry
17# about understanding everything the code does. Just enjoy!
18
19data() # browse pre-loaded data sets
20data(rivers) # get this one: "Lengths of Major North American Rivers"
21ls() # notice that "rivers" now appears in the workspace
22head(rivers) # peek at the data set
23# 735 320 325 392 524 450
24
25length(rivers) # how many rivers were measured?
26# 141
27summary(rivers) # what are some summary statistics?
28# Min. 1st Qu. Median Mean 3rd Qu. Max.
29# 135.0 310.0 425.0 591.2 680.0 3710.0
30
31# make a stem-and-leaf plot (a histogram-like data visualization)
32stem(rivers)
33
34# The decimal point is 2 digit(s) to the right of the |
35#
36# 0 | 4
37# 2 | 011223334555566667778888899900001111223333344455555666688888999
38# 4 | 111222333445566779001233344567
39# 6 | 000112233578012234468
40# 8 | 045790018
41# 10 | 04507
42# 12 | 1471
43# 14 | 56
44# 16 | 7
45# 18 | 9
46# 20 |
47# 22 | 25
48# 24 | 3
49# 26 |
50# 28 |
51# 30 |
52# 32 |
53# 34 |
54# 36 | 1
55
56stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
57# Take that, Bell curve fundamentalists.
58
59# The decimal point is 1 digit(s) to the left of the |
60#
61# 48 | 1
62# 50 |
63# 52 | 15578
64# 54 | 44571222466689
65# 56 | 023334677000124455789
66# 58 | 00122366666999933445777
67# 60 | 122445567800133459
68# 62 | 112666799035
69# 64 | 00011334581257889
70# 66 | 003683579
71# 68 | 0019156
72# 70 | 079357
73# 72 | 89
74# 74 | 84
75# 76 | 56
76# 78 | 4
77# 80 |
78# 82 | 2
79
80# make a histogram:
81hist(rivers, col = "#333333", border = "white", breaks = 25)
82hist(log(rivers), col = "#333333", border = "white", breaks = 25)
83# play around with these parameters, you'll do more plotting later
84
85# Here's another neat data set that comes pre-loaded. R has tons of these.
86data(discoveries)
87plot(discoveries, col = "#333333", lwd = 3, xlab = "Year",
88 main="Number of important discoveries per year")
89plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year",
90 main="Number of important discoveries per year")
91
92# Rather than leaving the default ordering (by year),
93# we could also sort to see what's typical:
94sort(discoveries)
95# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
96# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
97# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
98# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
99
100stem(discoveries, scale = 2)
101#
102# The decimal point is at the |
103#
104# 0 | 000000000
105# 1 | 000000000000
106# 2 | 00000000000000000000000000
107# 3 | 00000000000000000000
108# 4 | 000000000000
109# 5 | 0000000
110# 6 | 000000
111# 7 | 0000
112# 8 | 0
113# 9 | 0
114# 10 | 0
115# 11 |
116# 12 | 0
117
118max(discoveries)
119# 12
120summary(discoveries)
121# Min. 1st Qu. Median Mean 3rd Qu. Max.
122# 0.0 2.0 3.0 3.1 4.0 12.0
123
124# Roll a die a few times
125round(runif(7, min = .5, max = 6.5))
126# 1 4 6 1 4 6 4
127# Your numbers will differ from mine unless we set the same random.seed(31337)
128
129# Draw from a standard Gaussian 9 times
130rnorm(9)
131# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
132# [7] -0.59975593 0.57629164 1.08455362
133
134
135
136##################################################
137# Data types and basic arithmetic
138##################################################
139
140# Now for the programming-oriented part of the tutorial.
141# In this section you will meet the important data types of R:
142# integers, numerics, characters, logicals, and factors.
143# There are others, but these are the bare minimum you need to
144# get started.
145
146# INTEGERS
147# Long-storage integers are written with L
1485L # 5
149class(5L) # "integer"
150# (Try ?class for more information on the class() function.)
151# In R, every single value, like 5L, is considered a vector of length 1
152length(5L) # 1
153# You can have an integer vector with length > 1 too:
154c(4L, 5L, 8L, 3L) # 4 5 8 3
155length(c(4L, 5L, 8L, 3L)) # 4
156class(c(4L, 5L, 8L, 3L)) # "integer"
157
158# NUMERICS
159# A "numeric" is a double-precision floating-point number
1605 # 5
161class(5) # "numeric"
162# Again, everything in R is a vector;
163# you can make a numeric vector with more than one element
164c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1
165# You can use scientific notation too
1665e4 # 50000
1676.02e23 # Avogadro's number
1681.6e-35 # Planck length
169# You can also have infinitely large or small numbers
170class(Inf) # "numeric"
171class(-Inf) # "numeric"
172# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
173# this obviates Z-score tables.
174
175# BASIC ARITHMETIC
176# You can do arithmetic with numbers
177# Doing arithmetic on a mix of integers and numerics gives you another numeric
17810L + 66L # 76 # integer plus integer gives integer
17953.2 - 4 # 49.2 # numeric minus numeric gives numeric
1802.0 * 2L # 4 # numeric times integer gives numeric
1813L / 4 # 0.75 # integer over numeric gives numeric
1823 %% 2 # 1 # the remainder of two numerics is another numeric
183# Illegal arithmetic yields you a "not-a-number":
1840 / 0 # NaN
185class(NaN) # "numeric"
186# You can do arithmetic on two vectors with length greater than 1,
187# so long as the larger vector's length is an integer multiple of the smaller
188c(1, 2, 3) + c(1, 2, 3) # 2 4 6
189# Since a single number is a vector of length one, scalars are applied
190# elementwise to vectors
191(4 * c(1, 2, 3) - 2) / 2 # 1 3 5
192# Except for scalars, use caution when performing arithmetic on vectors with
193# different lengths. Although it can be done,
194c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6
195# Matching lengths is better practice and easier to read most times
196c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6
197
198# CHARACTERS
199# There's no difference between strings and characters in R
200"Horatio" # "Horatio"
201class("Horatio") # "character"
202class("H") # "character"
203# Those were both character vectors of length 1
204# Here is a longer one:
205c("alef", "bet", "gimmel", "dalet", "he")
206# => "alef" "bet" "gimmel" "dalet" "he"
207length(c("Call","me","Ishmael")) # 3
208# You can do regex operations on character vectors:
209substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
210gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
211# R has several built-in character vectors:
212letters
213# =>
214# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
215# [20] "t" "u" "v" "w" "x" "y" "z"
216month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
217
218# LOGICALS
219# In R, a "logical" is a boolean
220
221class(TRUE) # "logical"
222class(FALSE) # "logical"
223# Their behavior is normal
224TRUE == TRUE # TRUE
225TRUE == FALSE # FALSE
226FALSE != FALSE # FALSE
227FALSE != TRUE # TRUE
228# Missing data (NA) is logical, too
229class(NA) # "logical"
230# Use | and & for logic operations.
231# OR
232TRUE | FALSE # TRUE
233# AND
234TRUE & FALSE # FALSE
235# Applying | and & to vectors returns elementwise logic operations
236c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE
237c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE
238# You can test if x is TRUE
239isTRUE(TRUE) # TRUE
240# Here we get a logical vector with many elements:
241c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE
242c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE
243
244# FACTORS
245# The factor class is for categorical data
246# Factors can be ordered (like grade levels) or unordered (like colors)
247factor(c("blue", "blue", "green", NA, "blue"))
248# blue blue green <NA> blue
249# Levels: blue green
250# The "levels" are the values the categorical data can take
251# Note that missing data does not enter the levels
252levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green"
253# If a factor vector has length 1, its levels will have length 1, too
254length(factor("green")) # 1
255length(levels(factor("green"))) # 1
256# Factors are commonly seen in data frames, a data structure we will cover later
257data(infert) # "Infertility after Spontaneous and Induced Abortion"
258levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
259
260# NULL
261# "NULL" is a weird one; use it to "blank out" a vector
262class(NULL) # NULL
263parakeet = c("beak", "feathers", "wings", "eyes")
264parakeet # "beak" "feathers" "wings" "eyes"
265parakeet <- NULL
266parakeet # NULL
267
268# TYPE COERCION
269# Type-coercion is when you force a value to take on a different type
270as.character(c(6, 8)) # "6" "8"
271as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
272# If you put elements of different types into a vector, weird coercions happen:
273c(TRUE, 4) # 1 4
274c("dog", TRUE, 4) # "dog" "TRUE" "4"
275as.numeric("Bilbo")
276# =>
277# [1] NA
278# Warning message:
279# NAs introduced by coercion
280
281# Also note: those were just the basic data types
282# There are many more data types, such as for dates, time series, etc.
283
284
285
286##################################################
287# Variables, loops, if/else
288##################################################
289
290# A variable is like a box you store a value in for later use.
291# We call this "assigning" the value to the variable.
292# Having variables lets us write loops, functions, and if/else statements
293
294# VARIABLES
295# Lots of way to assign stuff:
296x = 5 # this is possible
297y <- "1" # this is preferred traditionally
298TRUE -> z # this works but is weird
299# Refer to the Internet for the behaviors and preferences about them.
300
301# LOOPS
302# We've got for loops
303for (i in 1:4) {
304 print(i)
305}
306# We've got while loops
307a <- 10
308while (a > 4) {
309 cat(a, "...", sep = "")
310 a <- a - 1
311}
312# Keep in mind that for and while loops run slowly in R
313# Operations on entire vectors (i.e. a whole row, a whole column)
314# or apply()-type functions (we'll discuss later) are preferred
315
316# IF/ELSE
317# Again, pretty standard
318if (4 > 3) {
319 print("4 is greater than 3")
320} else {
321 print("4 is not greater than 3")
322}
323# =>
324# [1] "4 is greater than 3"
325
326# FUNCTIONS
327# Defined like so:
328jiggle <- function(x) {
329 x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise
330 return(x)
331}
332# Called like any other R function:
333jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
334
335
336
337###########################################################################
338# Data structures: Vectors, matrices, data frames, and arrays
339###########################################################################
340
341# ONE-DIMENSIONAL
342
343# Let's start from the very beginning, and with something you already know: vectors.
344vec <- c(8, 9, 10, 11)
345vec # 8 9 10 11
346# We ask for specific elements by subsetting with square brackets
347# (Note that R starts counting from 1)
348vec[1] # 8
349letters[18] # "r"
350LETTERS[13] # "M"
351month.name[9] # "September"
352c(6, 8, 7, 5, 3, 0, 9)[3] # 7
353# We can also search for the indices of specific components,
354which(vec %% 2 == 0) # 1 3
355# grab just the first or last few entries in the vector,
356head(vec, 1) # 8
357tail(vec, 2) # 10 11
358# or figure out if a certain value is in the vector
359any(vec == 10) # TRUE
360# If an index "goes over" you'll get NA:
361vec[6] # NA
362# You can find the length of your vector with length()
363length(vec) # 4
364# You can perform operations on entire vectors or subsets of vectors
365vec * 4 # 32 36 40 44
366vec[2:3] * 5 # 45 50
367any(vec[2:3] == 8) # FALSE
368# and R has many built-in functions to summarize vectors
369mean(vec) # 9.5
370var(vec) # 1.666667
371sd(vec) # 1.290994
372max(vec) # 11
373min(vec) # 8
374sum(vec) # 38
375# Some more nice built-ins:
3765:15 # 5 6 7 8 9 10 11 12 13 14 15
377seq(from = 0, to = 31337, by = 1337)
378# =>
379# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
380# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
381
382# TWO-DIMENSIONAL (ALL ONE CLASS)
383
384# You can make a matrix out of entries all of the same type like so:
385mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6))
386mat
387# =>
388# [,1] [,2]
389# [1,] 1 4
390# [2,] 2 5
391# [3,] 3 6
392# Unlike a vector, the class of a matrix is "matrix", no matter what's in it
393class(mat) # "matrix" "array"
394# Ask for the first row
395mat[1, ] # 1 4
396# Perform operation on the first column
3973 * mat[, 1] # 3 6 9
398# Ask for a specific cell
399mat[3, 2] # 6
400
401# Transpose the whole matrix
402t(mat)
403# =>
404# [,1] [,2] [,3]
405# [1,] 1 2 3
406# [2,] 4 5 6
407
408# Matrix multiplication
409mat %*% t(mat)
410# =>
411# [,1] [,2] [,3]
412# [1,] 17 22 27
413# [2,] 22 29 36
414# [3,] 27 36 45
415
416# cbind() sticks vectors together column-wise to make a matrix
417mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
418mat2
419# =>
420# [,1] [,2]
421# [1,] "1" "dog"
422# [2,] "2" "cat"
423# [3,] "3" "bird"
424# [4,] "4" "dog"
425class(mat2) # matrix
426# Again, note what happened!
427# Because matrices must contain entries all of the same class,
428# everything got converted to the character class
429c(class(mat2[, 1]), class(mat2[, 2]))
430
431# rbind() sticks vectors together row-wise to make a matrix
432mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4))
433mat3
434# =>
435# [,1] [,2] [,3] [,4]
436# [1,] 1 2 4 5
437# [2,] 6 7 0 4
438# Ah, everything of the same class. No coercions. Much better.
439
440# TWO-DIMENSIONAL (DIFFERENT CLASSES)
441
442# For columns of different types, use a data frame
443# This data structure is so useful for statistical programming,
444# a version of it was added to Python in the package "pandas".
445
446students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"),
447 c( 3, 2, 2, 1, 0, -1),
448 c( "H", "G", "G", "R", "S", "G"))
449names(students) <- c("name", "year", "house") # name the columns
450class(students) # "data.frame"
451students
452# =>
453# name year house
454# 1 Cedric 3 H
455# 2 Fred 2 G
456# 3 George 2 G
457# 4 Cho 1 R
458# 5 Draco 0 S
459# 6 Ginny -1 G
460class(students$year) # "numeric"
461class(students[,3]) # "factor"
462# find the dimensions
463nrow(students) # 6
464ncol(students) # 3
465dim(students) # 6 3
466# The data.frame() function used to convert character vectors to factor
467# vectors by default; This has changed in R 4.0.0. If your R version is
468# older, turn this off by setting stringsAsFactors = FALSE when you
469# create the data.frame
470?data.frame
471
472# There are many twisty ways to subset data frames, all subtly unalike
473students$year # 3 2 2 1 0 -1
474students[, 2] # 3 2 2 1 0 -1
475students[, "year"] # 3 2 2 1 0 -1
476
477# An augmented version of the data.frame structure is the data.table
478# If you're working with huge or panel data, or need to merge a few data
479# sets, data.table can be a good choice. Here's a whirlwind tour:
480install.packages("data.table") # download the package from CRAN
481require(data.table) # load it
482students <- as.data.table(students)
483students # note the slightly different print-out
484# =>
485# name year house
486# 1: Cedric 3 H
487# 2: Fred 2 G
488# 3: George 2 G
489# 4: Cho 1 R
490# 5: Draco 0 S
491# 6: Ginny -1 G
492students[name == "Ginny"] # get rows with name == "Ginny"
493# =>
494# name year house
495# 1: Ginny -1 G
496students[year == 2] # get rows with year == 2
497# =>
498# name year house
499# 1: Fred 2 G
500# 2: George 2 G
501# data.table makes merging two data sets easy
502# let's make another data.table to merge with students
503founders <- data.table(house = c("G" , "H" , "R" , "S"),
504 founder = c("Godric", "Helga", "Rowena", "Salazar"))
505founders
506# =>
507# house founder
508# 1: G Godric
509# 2: H Helga
510# 3: R Rowena
511# 4: S Salazar
512setkey(students, house)
513setkey(founders, house)
514students <- founders[students] # merge the two data sets by matching "house"
515setnames(students, c("house", "houseFounderName", "studentName", "year"))
516students[, order(c("name", "year", "house", "houseFounderName")), with = F]
517# =>
518# studentName year house houseFounderName
519# 1: Fred 2 G Godric
520# 2: George 2 G Godric
521# 3: Ginny -1 G Godric
522# 4: Cedric 3 H Helga
523# 5: Cho 1 R Rowena
524# 6: Draco 0 S Salazar
525
526# data.table makes summary tables easy
527students[, sum(year), by = house]
528# =>
529# house V1
530# 1: G 3
531# 2: H 3
532# 3: R 1
533# 4: S 0
534
535# To drop a column from a data.frame or data.table,
536# assign it the NULL value
537students$houseFounderName <- NULL
538students
539# =>
540# studentName year house
541# 1: Fred 2 G
542# 2: George 2 G
543# 3: Ginny -1 G
544# 4: Cedric 3 H
545# 5: Cho 1 R
546# 6: Draco 0 S
547
548# Drop a row by subsetting
549# Using data.table:
550students[studentName != "Draco"]
551# =>
552# house studentName year
553# 1: G Fred 2
554# 2: G George 2
555# 3: G Ginny -1
556# 4: H Cedric 3
557# 5: R Cho 1
558# Using data.frame:
559students <- as.data.frame(students)
560students[students$house != "G", ]
561# =>
562# house houseFounderName studentName year
563# 4 H Helga Cedric 3
564# 5 R Rowena Cho 1
565# 6 S Salazar Draco 0
566
567# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE)
568
569# Arrays creates n-dimensional tables
570# All elements must be of the same type
571# You can make a two-dimensional table (sort of like a matrix)
572array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4))
573# =>
574# [,1] [,2] [,3] [,4]
575# [1,] 1 4 8 3
576# [2,] 2 5 9 6
577# You can use array to make three-dimensional matrices too
578array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2))
579# =>
580# , , 1
581#
582# [,1] [,2]
583# [1,] 2 8
584# [2,] 300 9
585# [3,] 4 0
586#
587# , , 2
588#
589# [,1] [,2]
590# [1,] 5 66
591# [2,] 60 7
592# [3,] 0 847
593
594# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES)
595
596# Finally, R has lists (of vectors)
597list1 <- list(time = 1:40)
598list1$price = c(rnorm(40, .5*list1$time, 4)) # random
599list1
600# You can get items in the list like so
601list1$time # one way
602list1[["time"]] # another way
603list1[[1]] # yet another way
604# =>
605# [1] 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
606# [34] 34 35 36 37 38 39 40
607# You can subset list items like any other vector
608list1$price[4]
609
610# Lists are not the most efficient data structure to work with in R;
611# unless you have a very good reason, you should stick to data.frames
612# Lists are often returned by functions that perform linear regressions
613
614##################################################
615# The apply() family of functions
616##################################################
617
618# Remember mat?
619mat
620# =>
621# [,1] [,2]
622# [1,] 1 4
623# [2,] 2 5
624# [3,] 3 6
625# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X
626# over rows (MAR = 1) or columns (MAR = 2)
627# That is, R does FUN to each row (or column) of X, much faster than a
628# for or while loop would do
629apply(mat, MAR = 2, jiggle)
630# =>
631# [,1] [,2]
632# [1,] 3 15
633# [2,] 7 19
634# [3,] 11 23
635# Other functions: ?lapply, ?sapply
636
637# Don't feel too intimidated; everyone agrees they are rather confusing
638
639# The plyr package aims to replace (and improve upon!) the *apply() family.
640install.packages("plyr")
641require(plyr)
642?plyr
643
644
645
646#########################
647# Loading data
648#########################
649
650# "pets.csv" is a file on the internet
651# (but it could just as easily be a file on your own computer)
652require(RCurl)
653pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/pets.csv")))
654pets
655head(pets, 2) # first two rows
656tail(pets, 1) # last row
657
658# To save a data frame or matrix as a .csv file
659write.csv(pets, "pets2.csv") # to make a new .csv file
660# set working directory with setwd(), look it up with getwd()
661
662# Try ?read.csv and ?write.csv for more information
663
664
665
666#########################
667# Statistical Analysis
668#########################
669
670# Linear regression!
671linearModel <- lm(price ~ time, data = list1)
672linearModel # outputs result of regression
673# =>
674# Call:
675# lm(formula = price ~ time, data = list1)
676#
677# Coefficients:
678# (Intercept) time
679# 0.1453 0.4943
680summary(linearModel) # more verbose output from the regression
681# =>
682# Call:
683# lm(formula = price ~ time, data = list1)
684#
685# Residuals:
686# Min 1Q Median 3Q Max
687# -8.3134 -3.0131 -0.3606 2.8016 10.3992
688#
689# Coefficients:
690# Estimate Std. Error t value Pr(>|t|)
691# (Intercept) 0.14527 1.50084 0.097 0.923
692# time 0.49435 0.06379 7.749 2.44e-09 ***
693# ---
694# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
695#
696# Residual standard error: 4.657 on 38 degrees of freedom
697# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
698# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
699coef(linearModel) # extract estimated parameters
700# =>
701# (Intercept) time
702# 0.1452662 0.4943490
703summary(linearModel)$coefficients # another way to extract results
704# =>
705# Estimate Std. Error t value Pr(>|t|)
706# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
707# time 0.4943490 0.06379348 7.74920901 2.440008e-09
708summary(linearModel)$coefficients[, 4] # the p-values
709# =>
710# (Intercept) time
711# 9.234021e-01 2.440008e-09
712
713# GENERAL LINEAR MODELS
714# Logistic regression
715set.seed(1)
716list1$success = rbinom(length(list1$time), 1, .5) # random binary
717glModel <- glm(success ~ time, data = list1, family=binomial(link="logit"))
718glModel # outputs result of logistic regression
719# =>
720# Call: glm(formula = success ~ time,
721# family = binomial(link = "logit"), data = list1)
722#
723# Coefficients:
724# (Intercept) time
725# 0.17018 -0.01321
726#
727# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
728# Null Deviance: 55.35
729# Residual Deviance: 55.12 AIC: 59.12
730summary(glModel) # more verbose output from the regression
731# =>
732# Call:
733# glm(
734# formula = success ~ time,
735# family = binomial(link = "logit"),
736# data = list1)
737
738# Deviance Residuals:
739# Min 1Q Median 3Q Max
740# -1.245 -1.118 -1.035 1.202 1.327
741#
742# Coefficients:
743# Estimate Std. Error z value Pr(>|z|)
744# (Intercept) 0.17018 0.64621 0.263 0.792
745# time -0.01321 0.02757 -0.479 0.632
746#
747# (Dispersion parameter for binomial family taken to be 1)
748#
749# Null deviance: 55.352 on 39 degrees of freedom
750# Residual deviance: 55.121 on 38 degrees of freedom
751# AIC: 59.121
752#
753# Number of Fisher Scoring iterations: 3
754
755
756#########################
757# Plots
758#########################
759
760# BUILT-IN PLOTTING FUNCTIONS
761# Scatterplots!
762plot(list1$time, list1$price, main = "fake data")
763# Plot regression line on existing plot
764abline(linearModel, col = "red")
765# Get a variety of nice diagnostics
766plot(linearModel)
767# Histograms!
768hist(rpois(n = 10000, lambda = 5), col = "thistle")
769# Barplots!
770barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow"))
771
772# GGPLOT2
773# But these are not even the prettiest of R's plots
774# Try the ggplot2 package for more and better graphics
775install.packages("ggplot2")
776require(ggplot2)
777?ggplot2
778pp <- ggplot(students, aes(x = house))
779pp + geom_bar()
780ll <- as.data.table(list1)
781pp <- ggplot(ll, aes(x = time, price))
782pp + geom_point()
783# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)
How do I get R? ¶
- Get R and the R GUI from http://www.r-project.org/
- RStudio is another GUI