-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9.3-function_example.R
More file actions
88 lines (57 loc) · 1.51 KB
/
9.3-function_example.R
File metadata and controls
88 lines (57 loc) · 1.51 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
# if-else
if(!is.factor(grade)) grade <- as.factor(grade) else print("grade already is a factor")
if(is.factor(grade)) grade <- as.factor(grade)
# ifelse
ifelse(score > 0.5, print("passed"),print("failed"))
# while
i <- 10
while(i > 0) {print("hello");i=i-1}
# for
for (i in seq(10)) {
print("hello")
}
# example 1
x <- c(0.05, 0.6, 0.3, 0.9)
for (i in seq(x)) {
if(x[i] <= 0.2) cat("small\n")
else if(x[i] <= 0.8) cat("medium\n")
else cat("large\n")
}
# example 2
mystats <- function(x,parametric=TRUE,print=FALSE){
if(parametric){
center <- mean(x);spread <- sd(x)
} else {
center <- median(x);spread <- mad(x)
}
if(print & parametric) {
cat("mean=",center,"\n","sd=",spread,"\n")
} else if (print & !parametric){
cat("median=",center,"\n","mad=",spread,"\n")
}
result <- list(center=center,spread=spread)
return(result)
}
set.seed(1234)
x <- rnorm(500)
y1 <- mystats(x)
y <- mystats(x,parametric = FALSE,print = TRUE)
# example 3
pvalues <- c(.0867,.0018,.0054,.0183,.5386)
ifelse(pvalues < .05,"significant","Not significant")
result <- vector(mode = "character",length = length(pvalues))
for (i in 1:length(pvalues)) {
if(pvalues[i] < .05) result[i] <- "significant"
else result[i] <- "Not significant"
}
# for (i in seq(length(pvalues))) print(i)
# example 4
f <- function(x,y,z=1){
result <- x + (2*y) + (3*z)
return(result)
}
f(2,3,4)
f(2,3)
f(x=2,y=3)
f(z=4,y=2,3)
args(f)