-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcourse3.R
More file actions
141 lines (96 loc) · 2.17 KB
/
course3.R
File metadata and controls
141 lines (96 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
############# System control
## basic R commands:
getwd()
dir()
## platform dependent commands
system('pwd')
system('ls')
## What is the file separator for my system?
.Platform$file.sep
## How can I make a file path that 'always works'
file.path('bar','foo','bar.txt')
############# Writing functions
## Bare bones:
myFun <- function(){}
myFun()
## A function that does something
myFun <- function(){1+2}
myFun()
## A function that does something based on inputs
myFun <- function(x,y){x+y}
myFun(x=2, y=3)
## A function with default values
myFun <- function(x=1,y=2){x+y}
myFun(2)
##########################################
## Exercise 1
##########################################
############# Flow control
##
2==2
## VS
1==2
## Other operators:
## !=
## >
## <
## >=
## <=
## If()
y <- 1
if(y==1){y<-pi}
y
## else
y <- 3
if(y==1){
y<-pi
}else{
y<-pi*2
}
y
## switch
centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
############# Looping in R
## First lets make a list to loop over...
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
x
## Using lapply
lapply(x, FUN=mean)
## Now lets consider some square data:
x <- cbind(x1 = c(3,4,1,5), x2 = c(9,7,6,2))
x
## and then loop by col
apply(x, 2, sort)
## mapply for listing over two vectors (or more) at once
mapply(paste, 1:3, LETTERS[1:3], MoreArgs = list(sep="_"))
## And for loops
for(i in 1:4){message('count ',i)}
##########################################
## Exercise 2
##########################################
############# Some basic debugging tools
## How long is something taking?
system.time(date())
## How can I step into a function and see whats happening?
## First mark it with debug()
debug(mean)
## Then call it
## mean(1:4)
## Then unmark it later
undebug(mean)
##########################################
## Exercise 3
##########################################
############# Literate programming:
## http://rmarkdown.rstudio.com/
##########################################
## Exercise 4
##########################################