5. 6
> g <- greeting
> g(name=" ", birthday="4 ")
[1] " 4 "
add() adder()
x y add
> add <- function(x, y, adder) {
+ adder(x, y)
+ }
add add.num() add add.str()
> add.num <- function(x, y) {
+ x + y #
+ }
> add.str <- function(x, y) {
+ paste(x, y) #
+ }
add()
> add(1, 5, add.num)
[1] 6
> add("a", "b", add.str)
[1] "a b"
> add("a", "b", function(x, y) {paste(x, y, sep="+")})
[1] "a+b"
3
I 5
6. 3.1 6
3.1
3.1.1 if
TRUE FALSE if if
> absolute.value <- function(x) {
+ if (x > 0) {
+ x # x > 0 TRUE x
+ } else {
+ -x # x > 0 FALSE x
+ }
+ }
> absolute.value(5)
[1] 5
> absolute.value(-9)
[1] 9
TRUE return(x) x
FALSE else
> absolute.value <- function(x) {
+ if (x > 0) {
+ return(x) # x > 0 TRUE x
+ }
+ -x # x > 0 FALSE x
+ }
> absolute.value(-100)
[1] 100
> absolute.value(4)
[1] 4
if-else 90 A 80
B 60 C D grade()
> grade <- function(score) {
+ if (score >= 90) {
+ "A"
+ } else if (score >= 80) {
+ "B"
+ } else if (score >= 60) {
+ "C"
+ } else {
+ "D"
+ }
+ }
> grade(100)
[1] "A"
I 6
7. 3.1 6
> grade(34)
[1] "D"
> grade(65)
[1] "C"
> grade(83)
[1] "B"
grade() else if { } else if
1 1
> grade <- function(score) {
+ if (score >= 90) {
+ "A"
+ } else {
+ if (score >= 80) {
+ "B"
+ } else {
+ if (score >= 60) {
+ "C"
+ } else {
+ "D"
+ }
+ }
+ }
+ }
if grade() if else
1
> grade <- function(score) {
+ if (score >= 90)
+ "A"
+ else if (score >= 80)
+ "B"
+ else if (score >= 60)
+ "C"
+ else
+ "D"
+ }
3.1.2 ifelse()
if-else ifelse() ifelse()
ifelse()
I 7
8. 3.2 6
ifelse( , , )
> absolute.value <- function(x) { # ifelse
+ ifelse(x > 0, x, -x)
+ }
> grade <- function(score) { # ifelse
+ ifelse(score >= 90, "A",
+ ifelse(score >= 80, "B",
+ ifelse(score >= 60, "C", "D")))
+ }
ifelse()
3.1.3 switch
if-else 2 switch()
switch( , 1, 2, 3, ...)
1
> switch(3, " 1", " 2", " 3", " 4") # 3
[1] " 3"
> switch("b", a=" 1", b=" 2", c=" 3") # b
[1] " 2"
3.2
R for while
R 3.4 apply
3.2.1 for
for
for(i in )
i i
{ }
I 8
9. 3.2 6
> z <- 0 # z 0
> for(i in 1:10) {
+ z <- z + i # 1 10
+ }
> z # for z
[1] 55
> for(n in c("a", "b", "c", "d")) #
+ cat(toupper(n), "n") # toupper()
A
B
C
D
for 2
> for(i in 1:5) {
+ for(j in 1:5)
+ cat(i, "-", j, ", ", sep="")
+ cat("n")
+ }
1-1, 1-2, 1-3, 1-4, 1-5,
2-1, 2-2, 2-3, 2-4, 2-5,
3-1, 3-2, 3-3, 3-4, 3-5,
4-1, 4-2, 4-3, 4-4, 4-5,
5-1, 5-2, 5-3, 5-4, 5-5,
3.2.2 while
while
> countdown <- function(n) { # n 0
+ while (n != 0) {
+ cat(n, ", ", sep="")
+ n <- ifelse (n >= 0, n-1, n+1) # n
+ }
+ cat("0n")
+ }
> countdown(10)
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
> countdown(-5)
-5, -4, -3, -2, -1, 0
I 9
10. 3.3 6
3.3
(1) (7) 3 GDP
ppp GDP
compare.gdp() 2010
> compare.gdp(ppp, 2010)
Qatar 117518.7
Japan 34986.99
Congo, Dem. Rep. 646.2954
(2) x y gcd(x, y)
3.4 apply
for while
R apply
apply 1
1 2 4 ? 3 2 ?
I 10