-
Notifications
You must be signed in to change notification settings - Fork 25
/
08_Functions.R
49 lines (39 loc) · 1.01 KB
/
08_Functions.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
x <- c("a", "b", "c", "d")
for (i in seq_along(x)) {
print(x[i])
}
for(letter in x) {
print(letter)
}
pow <- function(x = 4, n = 3) {
x^n
}
pow()
library(datasets)
data(iris)
?iris
mean(iris[iris$Species=='virginica', 1])
apply(iris[, 1:4], 2, mean)
library(datasets)
data(mtcars)
#How can one calculate the average miles per gallon (mpg) by number of cylinders in the car (cyl)?
split(mtcars$mpg, mtcars$cyl) #splits a vector (mpg) according to a factor [well, in this case coerced into] (cyl : 4,6, or 8)
sapply(split(mtcars$mpg, mtcars$cyl), mean) #powerful, kind of like group by cyl, mean(mpg)
sapply(split(mtcars$hp, mtcars$cyl), mean)
209.21429 - 82.63636
x <- matrix(rnorm(200), 20, 10) #200 random numbers in 20*10 matrix
apply(x, 1, quantile, probs=c(0.25,0.75)) #apply the quantile function, passing in its probs parameters
f <- function(x) {
g <- function(y) {
y + z
}
z <- 4
x + g(x)
}
z <- 10
f(3)
debug(ls)
ls
f1 <- gl(2,5); f1 #gl: generate factor levels
f2 <- gl(5,2); f2
interaction(f1, f2)