-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogramming_basics.R
95 lines (74 loc) · 1.55 KB
/
programming_basics.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
# ----- condicionais -----
library(dslabs)
data(murders)
murder_rate <- murders$total/murders$population*10^5
# if-else
ind <- which.min(murder_rate)
if(murder_rate[ind] < 0.5){
print(murders$state[ind])
} else{
print("no state has murder rate that low")
} #vermont
if(murder_rate[ind] < 0.25){
print(murders$state[ind])
} else{
print("no state has murder rate that low")
} #no state has murder rate that low
# ifelse
a <- c(0, 1, 2, -4, 5)
result <- ifelse (a > 0, 1/a, NA)
result # NA, 1.0, 0.5, NA, 0.2
data("na_example")
sum(is.na(na_example)) #145 NA's
no_nas <- ifelse(is.na(na_example), 0, na_example)
sum(is.na(no_nas)) #0 NA's
# any-all
z <- c(TRUE, TRUE, FALSE)
any(z) #TRUE
all(z) #FALSE
z <- c(FALSE, FALSE, FALSE)
any(z) #FALSE
all(z) #FALSE
z <- c(TRUE, TRUE, TRUE)
any(z) #TRUE
all(z) #TRUE
# ----- funções -----
# função mean()
avg <- function(x){
s <- sum(x)
n <- length(x)
s/n
}
x <- 1:100
avg(x) #50.5
identical(mean(x), avg(x)) #TRUE
avg <- function(x, arithmetic=TRUE){
n <- length(x)
ifelse(arithmetic, sum(x)/n, prod(x)^(1/n))
}
x <- c(1:100)
avg(x) #50.5
avg <- function(x, arithmetic=FALSE){
n <- length(x)
ifelse(arithmetic, sum(x)/n, prod(x)^(1/n))
}
x <- c(1:100)
avg(x) #37.9
compute_s_n <- function(n){
x <- 1:n
sum(x)
}
compute_s_n(100) #5050
# ----- loops -----
m <- 25
# criar um vetor vazio
s_n <- vector(length = m)
for(n in 1:m){
s_n[n] <- compute_s_n(n)
}
s_n
x <- 1:m
plot(x, s_n)
# algumas funções para ver:
# apply, sapply, tapply, mapply
# split, cut, quantile, reduce, identical, unique, etc