You are on page 1of 201

- R PDF -

R S
OS
S-plus

Windows R Mac OS X R Linux R


http : //cse.naro.af f rc.go.jp/takezawa/r tips/r.html PDF *1
R

R
R

R ()
()
The R Book ()
Introductory Statistics with R Peter Dalgaard (Springer)
R ( HP ) http : //aoki2.si.gunma u.ac.jp/R/
R
3
() ()
()
()

() \ Y Y R \ Y \
UNIX LINUX Mac OS \ Windows

Y OS

*1

4 2005 8 8 R 2.1.0 2.1.1

10

11

1.0

R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.1

R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.1

1.1.1

Windows R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.1.2

Mac OS X R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.1.3

Linux R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

16
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.1.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.1.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.1.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.1.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

2.1.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

2.1.6

R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.2

2.1.7

2.1.8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.1.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2.2.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1

. . . . . . . . . . . . . . . . . . . . . . . . 27

2 rgl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3 rgl . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4 rgl

. . . . . . . . . . . . . . . . . . . . . . . . 28

5 rgl unload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.2.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Windows R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Mac OS X R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

II

32

33

3.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.1.1
3.1.2
3.1.3
3.1.4
3.1.5
3.1.6
3.2

3.3
4

NULL

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

NA NaN Inf . . . . . . . . . . . . . . . . . . . . 33

numeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
logical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.2.1

print()

3.2.2

cat() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.2.3

sprintf() . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.2.4

str() . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.2.5

comment() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.2.6

sink() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

38

4.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

4.3

4.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

4.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

4.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.8

4.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

4.7.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.7.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.7.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4.7.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . 44

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4.8.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4.8.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4.8.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

NULLNANaNInf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.9.1

NULLNANaNInf . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

4.9.2

NA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

4.9.3

NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

48

5.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

5.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

5.5

5.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

5.5.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

5.5.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

5.5.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

5.5.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

5.5.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

5.6.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

5.6.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

5.6.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

5.6.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5.6.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

58

6.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

6.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

6.3

apply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

6.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

6.5

names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

III
7

7.1

7.2

7.3

7.4

7.5

67
68

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

7.1.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

7.1.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

7.1.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

7.1.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

7.2.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

7.2.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

7.2.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

7.3.1

if else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

7.3.2

switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

7.3.3

&& || . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

7.4.1

for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

7.4.2

while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

7.4.3

break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7.4.4

repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7.5.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7.5.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

7.5.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

7.5.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

7.5.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

7.5.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

7.5.7

<< . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

7.5.8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

7.5.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

7.5.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

7.6.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

7.6.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
missing()

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

7.6.3

7.6.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

7.6.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

7.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

7.8

7.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

7.9.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

7.9.2

readline() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

7.9.3

menu() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

86

8.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

8.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

8.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

8.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

8.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

8.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

8.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

8.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

8.8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

8.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

8.10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

8.11

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

IV

92

93

9.1

9.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

9.1.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

9.1.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

9.2.0

9.2.1

. . . . . . . . . . . . . . . . . . . . . . . . . 95

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

9.2.2

EXCEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

csv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
EXCEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
xls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
9.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

9.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

9.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

9.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

9.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

9.7.1

9.7.2

attach() detach() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

9.7.3

R . . . . . . . . . . . . . . . . . . . . . . 105

9.7.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

9.7.5

scan()

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

. . . . . . . . . . . . . . . . . . . . . 107

scan() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
scan() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

9.7.6
10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

110

10.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

10.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

10.3

EXCEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

10.4

LATEX html . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

113

11

114

11.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

11.2

11.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

11.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

11.5

plot()

11.6

plot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

11.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

11.8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

11.9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

11.10

11.11

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

12

12.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

121

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

12.1.1 plot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121


12.1.2 dotchart() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
12.1.3 stripchart() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
12.1.4 sunflowerplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

12.1.5 curve()

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

12.1.6 matplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122


12.1.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
12.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

12.2.1 hist() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123


12.2.2 barplot()

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

12.2.3 pie() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124


12.2.4 boxplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
12.2.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
12.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

12.3.1 fourfoldplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


12.3.2 mosaicplot()

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

12.3.3 assocplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


12.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
12.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

12.4.1 stars() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127


12.4.2 symbols() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.4.3 pairs() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.4.4 coplot() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.4.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.5

3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.1 image() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.2 persp() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.3 contour() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.4 scatterplot3d() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.5 lattice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
12.5.7 grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

13

131

13.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

13.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

13.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

13.4

eps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

13.4.1 Tgif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138


13.4.2 OpenOffice.org draw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
14

140

14.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

14.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

14.2.1 par() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141


14.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
14.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
14.2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
14.2.5 plot region . . . . . . . . . . . . . . . . 142

14.2.6 figure region . . . . . . . . . . . . . . . . . 143


14.2.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
14.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

14.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
14.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
14.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
14.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
14.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
14.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
15

147

15.1

locator() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

15.2

identify() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

15.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

15.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
15.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
layout() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
split.screen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
15.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

VI

153

16

154

16.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

16.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
16.1.2 . . . . . . . . . . . . . . . . . . . . . . . . 155
16.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
16.1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
16.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

16.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
16.3

R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
16.3.1 set.seed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
16.3.2 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
16.3.3 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
3 t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
16.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
16.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
16.3.6 2 x 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

16.4
17

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

163

17.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

17.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

17.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

17.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

17.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

17.6

lowess() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

18

18.1

18.2

170

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

18.1.1 (1) t

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

18.1.2 (2) t

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

18.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
18.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
18.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
18.2.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

18.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
t

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
U . . . . . . . . . . . . . . . . . . . 176
F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
. . . . . . . . . . . . . . . . . . . . . . . . 176

18.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

18.4.1 2 () . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

18.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
( 2 2 )

. . . . . . . . . . . . . . . . 178

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
( 2 2 ) . . . . . . . . . . . . . . . . . . . . . . . . 179
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

18.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
18.4.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
. . . . . . . . . . . . . . . . . . . . . 183
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
. . . . . . . . . . . . . . . . . . . . . . . . . 183

18.5
19

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

185

19.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

19.2

lsfit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

19.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

19.3.1 lm() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187


19.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
19.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
19.4

19.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

20

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

193

20.1

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

20.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

20.3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

20.4

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

20.5

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

20.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

20.7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

20.8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

200

200

11

1.0 R
RWeb ()http : //r.nakama.ne.jp/Rweb jp/ R R

1.1 R
R 2.1.0 *1 R

1.1.1 Windows R

http : //r.nakama.ne.jp/R 2.1.0/patched build/ rw2010pat.20050420.exe

!
!
#
#
"Next> $[I accept the agreement] "Next> $

*2

1.1

1.2

"Next> $ 1.4
[Chinese/Japanese/Korean installation]

*1
*2

R 2.1.1
R 2.1.1 CRANhttp : //cran.md.tsukuba.ac.jp/bin/windows/base/rpatched.html

12

1.3

1.4

[Message Translations] [Version for East Asian languages] 1.5


[Next>]

1.5

1.6

1.7 R

.Rdata

R R

"Next> $ 1.8

1.7

1.8

1.9 "Finish $
R etc

C : YP rogram F ilesYRYrw2010patYetc 1.10 Rconsole Rdevga

13

1.9

1.10

Rconsole Rdevga

Rconsole
17 font = TT Courier New -> font = TT MS Gothic
18 points = 10

-> points = 14

Rdevga12 15
TT Arial : plain

-> TT MS Gothic : plain

TT Arial : bold

-> TT MS Gothic : bold

TT Arial : italic

-> TT MS Gothic : italic

TT Arial : bold&italic -> TT MS Gothic : bold&italic

R
[R] [R 2.1.0 patched] [R 2.1.0 patched]
R

14

1.1.2 Mac OS X R
R-2.1.0.dmg (Mac OS X 10.3 ) R-2.0.1.dmg (Mac OS X 10.2) The R Project
http : //cran.md.tsukuba.ac.jp/bin/macosx/
R 2.1.0 mpkg

1.11

1.12

%
'
2 & (

1.13

1.14

"Continue $
Agree

&

1.16

1.15

'

%
&

'

'

%
&

'

&

15

1.17

1.18

1.19 [Finish]

1.19

1.20

R
[R] R
1.20

1.1.3 Linux R
Linux R RjpWikihttp : //www.okada.jp.org/RW iki/index.php?RjpW iki
RjpWiki R
Wiki
Linux R

16

2.1
2.1.1
R OS
Windows [R 2.1.0 Patched]
[R] [R 2.1.0 Patched]

Mac OS X Finder [R]


Linux Linux kterm R
[Gnu R]

R R
R : Copyright 2005, The R Foundation for Statistical Computing
Version 2.1.0 Patched (2005-04-20), ISBN 3-900051-07-0
R

license() licence()

R
contributors()
R R

citation()
demo()
help()
help.start() HTML
q() R
>
!
#
! #
" $ "Enter $

*1 R
>

*1

> options(prompt= ) (options(prompt=: ) )

17

! #
> 1+2 " $
[1] 3

! #
> sin(pi/2) " $
[1] 1

>

R *2

(1) R
(2) R
! #
" $ R
!
#
> 1 + 2 "Enter $
> 1 + 2 R

2.1.2
2 R

! #
> q() " $
! #
> quit() " $

Windows [] []
%
' %
'
&

( &

2.2

2.1

Mac OS X [R] [R ]
%
' %
'
&

( &

*2

1 + 2 3 [1]

18

2.4
2.3

save.image()

! #
> save.image("C:/filename.RData") " $

2.1.3
R ( )

%/%

%%

! #
> (1 + 2 - 3 * 4) / 5^6 " $
[1] -0.000576

sqrt(2) sqrt()

! #
> sqrt(2) " $
[1] 1.414213

! #
> sqrt(100) + round(100) / log10(100) " $
[1] 60

R x 2.0 0.5

sin(x)

cos(x)

tan(x)

sinh(x)

cosh(x)

tanh(x)

sin

cos

tan

sinh

cosh

tanh

asin(x)

acos(x)

atan(x)

asinh(x)

acosh(x)

atanh(x)

sin

cos

tan

sinh

cosh

tanh

log(x)

log10(x)

log2(x)

log1p(x)

exp(x)

expm1(x)

log(1+x)

exp(x)1

sqrt(x)

round(x)

trunc(x)

floor(x)

ceiling(x)

signif(x,a)

x a

19

2.1.4
R (object)

*3 = ;

x 2

!
> x <- 2 "
! #
> x " $
[1] 2
!
> x + 3 "
[1] 5

!
#
$

#
$

x < 2 x + 3
2 + 3

! #
> x <- 2 " $
! #
> x <- 3 " $
> x

!
!

! #
> y <- x " $
[1] 3

< *4

<

>

assign(, )

()

! #
> (x <- 1:4) " $
[1] 1 2 3 4

R *5

else

for

function

if

in

next

2.1.5
! #

! #

" $

repeat

! #

" $

return

while

TRUE

FALSE

" $

! #
" $

break

*6
*3

A3 3A
*4 y < x < 10
*5 objects()
x x rm() rm(list=ls(all=TRUE))

*6 history()

20

2.1.6 R
R 1 R
1
R

Windows
[] [] R

2.6

2.5

[] [ R ]
!
# ! # ! #
"Ctrl $+"R $ "F5 $*7

2.7

*7

R
!
#! #
"Ctrl $+"R $

2.8

#! #

"Ctrl $+"A $

21

Mac OS X
[] [] R

2.9

2.10

!
# ! #
[] [] "Command $+" $ *8

2.12

2.11

Linux
vi Emacs R
Emacs XEmacs R ESS (Emacs

Speakes Statistics)*9 ESS ESS RjpWiki


The R Book
55 56

! #
" $

R R R > +

> (1 + 2 - 3 * 4) / 5^6

[1] -0.000576
!
#! #
R "Command $+"A $
!
#! #
"Command $+" $
9

*8

http : //stat.ethz.ch/ESS/

22

#
# *10

> (1 + 2 - 3 * 4) / 5^6

[1] -0.000576

(1 + 2 3 4) / 56

2.1.7

( R )
*11 R
*12

> setwd("c:/usr")

> getwd()

[1] "c:/usr"
Windows [] [...]

2.14

2.13

Mac OS X [] [...]

*10

R
Windows Ysetwd(c:Yusr) setwd(c:/usr)
*12 dir()
*11

23

2.15

2.16

2.1.8
solve() 2 solve
*13

> help(solve)
> ?solve
R

> ?Syntax
for [ (> ?for )
> help("for")
solve help.search(
) *14

> help.search("solve")

2.1.9

(a) R x X R
(b) sin
2

> 1

[1] 3
> 1 + 2
[1] 3

*13
*14

args(solve)
RSiteSearch() R-help mailing list R R

24

(c) ;
> 1+2;

3-4

[1] 3
[1] -1
(d) R
> +

> 1 +
+ 2
[1] 3
2 + +1 + +2>
!

+1 + 2

"Esc $
() S-PLUS S

+ Continue string: +
R

(e) R x

> x <- c(1,2)


x (1, 2)

> x
[1] 1 2
(f) (
> x <- c(1, 2)

> (x <- c(1, 2))

[1] 1 2
> f <- function(x) y <- 2*x
> f( c(1, 2) )

> f <- function(x) (y <- 2*x)


> f( c(1, 2) )

[1] 2 4
(g) R
solve()
> example(solve)
example()

> par(ask = TRUE)

25

(h) Windows R [
] [] 2.17 [
] [] 2.18

2.17

2.18

.r.q

2.19

Mac OS X R
[] [] 2.20
[] [] 2.21

26

2.20

2.21

2.22

source.txt

> source("C:/source.txt")

data.txt
R Windows
22
C:YProgram FilesYRYrw2010pat Mac OS X /Users/*15

*15

source.txt source(source.txt) R .Rprofile


source(source.txt) R save() Rdata
attach()

> myfunc <- function(x) x^2


> save(myfunc, file="source.Rdata")
... ...
> attach("source.Rdata")

27

2.2
R
library()

> library()

base

boot

RS-Plus

class

Classification

cluster

foreign

R ( SAS )

grid

KernSmooth

lattice

MASS

Modern Applied Statistics with S

methods

R ,

mgcv

(GCV,GAM)

nlme

nnet

rpart

regression trees

spatial

splines

stats

stats4

S4

survival

tcltk

Tcl/Tk

tools

utils

2.2.1
500 2005 6

> library(help="<>")
( base )
library()
1

> search()

28

2 rgl

> library(rgl)
3 rgl

> example(rgl.surface)
>
> n <- 100
> rgl.clear()
> rgl.bg(color=c("white", "black"))
> rgl.spheres(rnorm(n), rnorm(n), rnorm(n), radius=0.2, color=rainbow(10))
> rgl.bbox(color="#333377")

2.23

2.24

volcano

rgl

rgl.open()

rgl.set()

rgl.cur()

rgl.close()

rgl.clear()

rgl.pop()

rgl.quit()

rgl.viewpoint()

rgl.light()

rgl.bg()

rgl.points()

rgl.sprites()

rgl.lines()

rgl.triangles()

rgl.quads()

rgl.texts()

rgl.surface()

rgl.spheres()

rgl.snapshot()

rgl.bbox()

4 rgl

> library(help="rgl")
> help(package="rgl")

29

5 rgl unload

> detach("package:rgl")
CRAN update.packages()

Windows R R rgl

rgl R
rgl

> help.search("solve")

# solve

> help(package="MASS")

# MASS

> base::log

# base log

> base::"+"

# base "+"

> grid::grid.newpage()

# grid

> data()

> data(package = "base")

# base

> data(USArrests, "VADeaths") # USArrests VADeaths


> help(USArrests)

# USArrests

2.2.2
R-Project CRAN
RjpWiki CRAN CRAN
CRAN URL CRAN.packages() install.packages()
xtable

> options(CRAN="http://cran.r-project.org")
> install.packages("xtable")
install.packages()
xtable 1.2-3.zip

> install.packages("c:/xtable_1.2-3.zip", CRAN = NULL)


Windows R
Windows R GUI
[] [] *16 CRAN
*17

*16
*17

installed.packages()
CRAN.packages()

30

2.25

2.26 CRAN

"OK $
2.27

[] [] 2.28
"OK $ 2.29

2.28
2.27

2.29

Windows R R
--internet2C:YProgram

FilesYRYrw2010YbinYRgui.exe --internet2

2.30

31

Mac OS X R

Mac OS X R GUI
%
'
[] []
&
(

2.31

2.32 CRAN

"OK $

2.33

2.34

[] []

'

&

2.35

II

33

3.1
R

3.1.1 NULL
R NULL 0 NULL 0
names for

NULL
+

> x <- c()

3.1.2 NA NaN Inf


)

(Not Available) NA (Not a Number) NaN

> NA

[1] NA
> 0/0

[1] NaN
> 1/0

# NaN Inf

[1] Inf
+

3.1.3 numeric
)

1e10 1 10(10) = 10000000000 pi

> 123

[1] 123
> 1e10
[1] 1e+10
+

# 10^(10)
,

34

3.1.4 complex
1 1+0i 1 + i 1+1i 1+i i
)

*1

> 1 + 1i
[1] 1+1i
> 1 + 0i

# 1

[1] 1+0i
+

3.1.5 character
1 *2
)

> "abc"

[1] "abc"
# " 2

> ""
[1] ""
+

# " " ()

3.1.6 logical
TRUE () FALSE () TF *3 TRUE

FALSE
)
> T

[1] TRUE
> TRUE
[1] TRUE
+

*1

2 2+0i

> log(-2)
[1] NaN

NaN in: log(x)

> log(-2+0i)
[1] 0.6931472+3.141593i

*2
*3

Y
T F TRUE FALSE T F TRUE FALSE

35

3.2

3.2.1 print()
print() *4

> x <- "one"


# ""

> print(x)
[1] "one"
> print(x, quote=F)

# ""

[1] one

3.2.2 cat()
cat() print()
cat() *5 YYYt Yn Yf
Y*6 Y 3 8

> cat("cd C:\\Document and Settings\\usr\\ \n")

cd C:\Document and Settings\usr


cat() Yn

3.2.3 sprintf()
sprintf() *7

sprintf(%5.1f, )

3 1 1

sprintf(%f, )

f 6

sprintf(%10f, )

% f + 0

sprintf(%3d, as.integer())

3
%3i

sprintf(%e, )

g G

sprintf(%s, as.character())
*4

as.character()

page()

*6 OS Y \ Y
*7 formatC()
*5

36

%5.0f 5

> sprintf("%5.0f", 1234.5678)


[1] " 1235"

3.2.4 str()
str()

summary()
> str(x)
chr "12345"
> summary(x)
Length

Class

Mode

1 character character

3.2.5 comment()
comment()
comment() str()

> x <- "Washi"


> comment(x) <- "my handle name"
> x
[1] "Washi"
> comment(x)
[1] "my handle name"

3.2.6 sink()
R sink()
dump()dget()dput()capture.output()

> sink("output.txt")

# output.txt

> sink()

37

3.3
options() options() *8

continue

device

(x11, windows, gtk)

digits

expressions

500

prompt

>

scipen

show.error.messages

TRUEFALSE

timeout

60

warn

0
1 2

width

80

CRAN

CRAN URL http : //cran.r project.org

7 digits ()

> options(digits=10)
2

# 10

10000 100000 1e5 scipen

> options(scipen=0);

print(1e5)

[1] 1e+05
> options(scipen=1);

print(1e5)

[1] 100000
3

width

> x <- runif(6)


> x
[1] 0.49152403 0.65764434 0.02852227 0.34614703 0.37701605 0.42428670
> options(width=50)
> x
[1] 0.49152403 0.65764434 0.02852227 0.34614703
[5] 0.37701605 0.42428670

*8

help(options)

38

> 1 + 2
[1] 3
1 + 2 3 [1] 1 1

(1) 1 1 (2) 1 1 (3) [1]

4.1
c() *1

> c(1.0, 2.0, 3.0, 4.0, 5.0)

# 5

[1] 1 2 3 4 5
< c()
c

> ( c <- c(1.0, 2.0, 3.0, 4.0, 5.0) ) # c


[1] 1 2 3 4 5
length()

# 5

> length(x)
[1] 5

c()

# 1

> 1:5
[1]

> 3:-3
[1] 3 2 1 0 -1 -2 -3

*1

5 1

# 3 -3 1

39

# (1 2 3) 8

> rep(1:3, length=8)


[1] 1 2 3 1 2 3 1 2

# 1 10 5

> seq(1, 10, length=5)


[1] 1.00 3.25 5.50 7.75 10.00

# 1:length(c(2,8,5))

> seq(along=c(2,8,5))
[1] 1 2 3

a:b

a b (a < b) 1 a > b 1

seq(a, b, length = n)

a, b n

seq(a, b, by = c)

a b c

sequence(c(3,2))

(1 2 3 1 2)

rep(a:b, times = c)

a b 1 c c

rep(a:b, length = c)

a b 1 c

unique(x)

numeric(n)

0 n

4.2
()
+ () () () / () %/% ()%% () ()

> c(1, 2, 3) + c(4, 5, 6)

# c(1+4, 2+5, 3+6)

[1] 5 7 9
> c(1.0, 2.0) * c(3.0, 4.0)

# c(1*3, 2*4)

[1] 3 8

> c(6.0, 5.0, 4.0, 3.0) - c(2.0, 1.0)

# c(6-2, 5-1, 4-2, 3-1)

[1] 4 4 2 2
> c(1.0, 2.0, 3.0, 4.0, 5.0) - 1

# 1

[1] 0 1 2 3 4
#

> 1 / 2:5
[1] 0.5000000 0.3333333 0.2500000 0.2000000

< == >

> c(1, 20, 300, 4, 50) == c(1, 2, 3, 4, 5)


[1]

TRUE FALSE FALSE

== 3

...

TRUE FALSE

> c(1, 20, 300, 4, 50) > 60


[1] FALSE FALSE

# 1 == 1, 20 == 2, 30

TRUE FALSE FALSE

# 1 > 60, 20 > 60, 300 >

60 ...

40

4.3
18
> sqrt(1:5)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068

(sqrt() cos() )
NA NA

sum()

mean()

var()

median()

cor()

max()

min()

prod()

cumsum()

sd()

sort()

rev()

pmax()

pmin()

range()

match()

diff()

rank()

order()

*2

> x <- 1:5


# x

> rev(x)
[1] 5 4 3 2 1
> y <- cumsum(x)

# y x

> mean(y)

# y

[1] 7
> mean(y, 0.5)

# y

[1] 6

# 100*0.5%=50% (trimmed mean)

> y <- c(0, 1, 3, 6, 10);


# y

> sort(y)
[1]

6 10
# y

> order(y)
[1] 1 2 3 4 5

# y

> rank(y)
[1] 1 2 3 4 5
> z <- c(100, 20, 4, 2, 1)

# x, y, z

> pmax(x, y, z)
[1] 100

20

> pmin(x, y, z)

10
# x, y, z

[1] 0 1 3 2 1

*2

cumsum() cumsum() ,
cumprod(), cummax(), cummin()

41

4.4

union(x, y)

intersect(x, y)

setdiff(x, y)

setequal(x, y)

is.element(x, y)

x y x%in%y

> x <- 1:5;

y <- 1:4
#

> intersect(x, y)
[1] 1 2 3 4

> setequal(x, y)
[1] FALSE

# x y

> is.element(x, y)
[1]

TRUE

TRUE

TRUE

TRUE FALSE

4.5
1, 2, x

x[k]

k 0 0

x[k] < a

k a

x[]

x[]

x[]

TRUE

x[]

x[]

names

*3

> x <- c(1, 2, 3, 4, 5)


> x[3]

# 3

[1] 3
> x[5] <- 0

# 5 0

> x

# x

[1] 1 2 3 4 0

*3

Mathematica Maple R

42

*4

> x <- c(1, 2, 3, 4, 5)


# 2 5

> x[2:5]
[1] 2 3 4 5

# 1 3

> x[c(-1,-3)]
[1] 2 4 5

# 30

> x[30 < x]


[1] 40 50

# 2 & |

> x[10 < x & x < 40]


[1] 20 30
> (1:length(x))[10 < x & x < 40]

[1] 2 3
which() *5

> x <- 1:10


> num <- which( abs(x-5.2) == min(abs(x-5.2)) )

# 5.2

> x[num]

[1] 5

4.6
replace()

> x <- c(1, 2, 3, 4, 5)

# x <- 1:5

> ( y <- replace(x, c(2,4), c(0,0)) )

# x 2, 4 0

[1] 1 0 3 0 5
> ( z <- replace(x, c(2,4), NA) )
[1]

1 NA

3 NA

> replace(z, which(is.na(z)), 10)


[1]

1 10

# NA

4 10

7 10

# z NA 10

2 c() 2 append()
append()

> x <- c(1, 2, 3);

y <- c(4, 5, 6);

z <- c(7, 8, 9)

> c(x, y, z)
[1] 1 2 3 4 5 6 7 8 9
> ( w <- append(x, z) )

# c(x, z)

[1] 1 2 3 7 8 9
> append(w, y, after=3)

# w 3 y

[1] 1 2 3 4 5 6 7 8 9

*4

& | == 70 [ ]
NA

*5 which.max(), which.min()

43

4.7

4.7.1
*6

> c(1+1i, 2+3i)

# 1+i 1+1i

[1] 1+1i 2+3i

# 1+i i

> complex(re=1:3, im=4:6)

# re

im

[1] 1+4i 2+5i 3+6i


> complex(mod=c(1,2), arg=c(0, pi))
[1]

# modarg

1+0.000000e+00i -2+2.449213e-16i

Re(z)

Im(z)

Mod(z)

abs(z)

Arg(z)

Conj(z)

4.7.2
TRUEFALSETF
& () | () ! () xor ()

>

c(T, F, T) | c(TRUE, FALSE, FALSE)

[1]

TRUE FALSE

TRUE

> !c(T, F, T)
[1] FALSE

TRUE FALSE

> xor( c(TRUE, FALSE, TRUE), c(TRUE, FALSE, FALSE) )


[1] FALSE FALSE

TRUE

any()

TRUE TRUE

all()

TRUE TRUE

> x <- seq(0, 1, 0.2)


> any(x > 0.8)

# x 1 0.8

[1] TRUE
> all(x < 0.8)

# x 0.8

[1] FALSE

*6

44

4.7.3

> c("HOKKAIDO", "SENDAI", "TOKYO", "NAGOYA", "OSAKA", "HAKATA")


[1] "HOKKAIDO" "SENDAI"

"TOKYO"

"NAGOYA"

"OSAKA"

"HAKATA"

ASCII

> "TOKYO" > "OSAKA"


[1] TRUE
> "HAKATA" > "OSAKA"
[1] FALSE

4.7.4
factor() levels()
str()

> x <- rep(c("L", "M", "H"), 9)


#

> ( fc <- factor(x) )

[1] L M H L M H L M H L M H L M H L M H L M H L M H L M H
Levels: H L M
# "L", "M", "H" ...

> levels(fc)
[1] "H" "L" "M"

levels

> ( fc <- factor(x, levels=c("L", "M", "H")) )


[1] L M H L M H L M H L M H L M H L M H L M H L M H L M H
Levels: L M H
factor() ordered()

> fc <- ordered(x)


#

> str(fc)

Ord.factor w/ 3 levels "H"<"L"<"M": 2 3 1 2 3 1 2 3 1 2 ...


gl(, , )

> gl(2, 10, 20)


[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
Levels: 1 2
> gl(2, 8, label = c("Control", "Treat"))
[1] Control Control Control Control Control Control Control Control
[9] Treat

Treat

Treat

Levels: Control Treat

Treat

Treat

Treat

Treat

Treat

45

4.8
4.8.1
paste()
*7

> paste("May I", "help you ?")


[1] "May I help you ?"
> paste(month.abb, 1:12, c("st", "nd", "rd", rep("th",9)) )
[1]

"Jan 1 st"

"Feb 2 nd"

"Mar 3 rd"

"Apr 4 th"

"May 5 th" "Jun 6 th"

[7]

"Jul 7 th"

"Aug 8 th"

"Sep 9 th" "Oct 10 th" "Nov 11 th" "Dec 12 th"

2 1 sep (
) collapse ()
sep

> paste("/usr", "local", "bin", sep = "/")

# /

[1] "/usr/local/bin"
> ( x <- paste(1:4) )
[1] "1" "2" "3" "4"
> paste(x, collapse="abc")
[1] "1abc2abc3abc4"
> paste(x, collapse="")
[1] "1234"

4.8.2
substring()

> substring("abcdefg", 2, 5)

# substring( , , )

[1] "bcde"

4.8.3 R
eval(parse(text=)) eval.parent(parse(text=))

> a <- numeric(5);

x <- 1:5

> for(i in x) eval(parse(text=paste("a[",i,"] <- 10", sep="") ))


> a
[1] 10 10 10 10 10

*7

R LETTERS () letters () month.abb (


) month.name () pi () 5

46

charmatch()

chartr()

grep(), match()

gsub(), sub()

nchar()

pmatch()

toupper()

tolower()

()

strsplit()

strwrap()

substr()

()

4.9 NULLNANaNInf
4.9.1 NULLNANaNInf
NULL () NA () NaN () Inf () NA
NAN NaN NaN
==

> x <- c(1.0, NA, 3.0, 4.0)

# NA ...

> x == NA

# NA NA

[1] NA NA NA
4 NA

is.na() ( == ) NaN TRUE


NaN (NA ) is.nan()

is.null()

is.na()

is.nan()

is.finite()

is.infinite()

complete.cases()

NULL

NA

NaN

> is.na(NA)
[1] TRUE
> is.nan(NA)
[1] FALSE
> x <- c(1, NA, 3, 4)
> is.na(x)
[1] FALSE TRUE FALSE FALSE

4.9.2 NA
NA NA

> a <- c(1, 2, NA, 4, 5, NA)


> a[!is.na(a)]

# a NA

[1] 1 2 4 5
> a <- ifelse(is.na(a), 0, a)
> a
[1] 1 2 0 4 5 0

# NA 0

47

NA NA NA

> x <- c(1, 2, NA, -4, 5, -6, 7, NA, 9, 10)


# NA x y

> y <- x[!is.na(x)]


> y
[1] 1 2 -4 5 -6 7 9 10

> x <- c(1, 2, NA, -4, 5, -6, 7, NA, 9, 10)


> y <- x[(!is.na(x)) & (x > 0)]

# NA x

> y

# y

[1] 1

9 10

4.9.3 NULL
NULL
NULL NA NA NULL

> length(NULL)

# "NULL"

[1] 0

# 0

> a <- 1:3


# names NULL

> names(a)
NULL

NULL

> names(a) <- c("a", "b", "c")


> a
a b c
1 2 3
> names(a) <- NULL
> a
[1] 1 2 3
NULL *8

> x <- NULL

# 0 x

> for (i in 1:10) x <- append(x, i*i)

# x i^2

> x
[1]

*8

16

25

36

49

64

81 100

x < c() x < numeric(0) as.characteras.numeric NULL


0

48

5.1
R *1
)

(2) matrix(, , )
+
!
"
1 3 5
(1, 2, 3, 4, 5, 6)

2 4 6

(1)

> matrix(1:6, nrow=2, ncol=3)


[,1] [,2] [,3]
[1,]

[2,]

# nrow ncol
# matrix(1:6, 2, 3)

() (
) byrow=T

> matrix(1:6, nrow=2, ncol=3, byrow=T)

# matrix(1:6, 2, 3, byrow=T)

[,1] [,2] [,3]


[1,]

[2,]

5.2
1, 2, 1, 2, *2

x [ ]

> ( x <- matrix(1:6, nrow=2, ncol=3) )


[,1] [,2] [,3]
[1,]

[2,]

*1

R 2 R 2
array()

*2 x[k] 1 1, 2, 2

49

> x[1, 2]
[1] 3
# 1 2 1,3

> x[-1, c(T,F,T)]


[1] 2 6

x[2, ]

rowSums()

x[ ,2]

colSums()

x[1, 2]

1 2

rowMeans()

x[c(1,2), 2]

1,2 2

colMeans()

x[c(1,2), c(1,3)]

1, 2 1, 3

x[,c(1, 3)]

1, 3

x[, c(T,F,T)]

1, 3

[ ]
> x[matrix(c(1,2,2,3), 2, 2)]

[1] 3 6

# x[cbind(c(1,2), c(3,4))]

> x[1:4]

[1] 1 2 3 4

# 4

drop=FALSE
()

# 2

> x[ ,2, drop=F]


[,1]
[1,]

[2,]

5.3
rbind()
cbind()

> ( x <- rbind(c(1,2,3), c(4,5,6)) )

[,1] [,2] [,3]


[1,]

[2,]

> ( x <- cbind(c(1,2,3),c(4,5,6))


[,1] [,2]
[1,]

[2,]

[3,]

50

3
> ( x <- rbind(1:3, c(4, 5, 6), 7:9) )

# 3

[,1] [,2] [,3]


[1,]

[2,]

[3,]

> ( y <- cbind(1:3, c(4, 5, 6), 7:9) )

# 3

[,1] [,2] [,3]


[1,]

[2,]

[3,]

5.4
*3

> a <- matrix(1:4, 2, 2)

# 2 * 2

> b <- matrix(0:3, 2, 2)

# 2 * 2

> a + b - a %*% b

> a * b

> a %o% b

# outer(x,y)

> a %x% b

%%

outer(x, y, FUN) FUN 2

> x <- seq(-3,3,0.1); y <- seq(-3,3,0.1)


> f <- function(x,y) 1/(2*pi)*exp(-(x^2+y^2)/2)
> z <- outer(x,y,f)

# persp(x,y,z,expand=0.5) 3

> a <- matrix(c(1,2,3,4), 2, 2)

# 2 * 2

> a * (1:2)

# (1:2) * a

[,1] [,2]
[1,]

[2,]

> 1/a
[,1]

[,2]

[1,]

1.0 0.3333333

[2,]

0.5 0.2500000

*3

kronecker()

51

5.5
R

matrix(0,nrow=2,ncol=3)

2 3 matrix(1,nrow=2,ncol=3)

diag(3)

3 3 diag(1, ncol=2, nrow=2), diag(1, 3), diag(rep(1, 3)),


diag(c(1,1))

diag(1:3)

(1 2 3) 3 3

diag(X) < 1

X 1

diag(x) < c(1, 2)


t(X)

2 2 X (1 2)
X

X[upper.tri(X)] < 0

() 0 0 up-

per.tri(X,diag=TRUE)
X[lower.tri(X)] < 0

() 0

sum(X2)

sum(diag(t(X)%%X))

solve(X)

ginv(X)

X library(MASS)

crossprod(X)

X t(X)%%X

crossprod(X,Y)

X Y t(X)%%Y

eigen(X)

qr(X)

X QR

chol(X)

X X = t(A)

%% A A
svd(X)

X X = U %% D %% t
X D V
U

det(X)

X prod(svd(X)$d)

5.5.1

> ( x <- matrix(c(1,2,0,3), 2, 2) )


[,1] [,2]
[1,]

[2,]

> y <- x+t(x)

> diag(y) <- diag(y)/2

> y

# y
[,1] [,2]

[1,]

[2,]

52

5.5.2
A.x = b x solve()
> a <- matrix(c(0,1,2,3,4,5,6,7,9), 3,3)

3y + 6z =

> b <- matrix(c(1,0,-2))

x + 4y + 7z =

> solve(a,b)

# 2x + 5y + 9z = -2

[,1]
[1,] -2.333333
[2,]

2.333333

[3,] -1.000000
backsolve() backsolve()
0
forwardsolve()

> r <- rbind(c(1,2,3),

# x + 2y + 3z = 8

c(0,1,1),

c(0,0,2))

y +

z = 4
2z = 2

> ( y <- backsolve(r, x <- c(8,4,2)) )

> r %*% y

# (8

> ( y2 <- backsolve(r, x, transpose = TRUE))

# (8 -12 -5)

2)

> all(t(r) %*% y2 == x)


> all(y

== backsolve(t(r), x, upper = FALSE, transpose = TRUE) )

> all(y2 == backsolve(t(r), x, upper = FALSE, transpose = FALSE))

5.5.3
( ) eigen()

> X <- matrix(c(1,2,3,4), 2, 2)


# X

> z <- eigen(X)


> z$values
[1]

5.3722813 -0.3722813
#

> z$vectors[,1]

5.3722813

[1] -0.5657675 -0.8245648


# -0.3722813

> z$vectors[,2]
[1] -0.9093767

0.4159736

53

5.5.4
svd()

> A <- array(c(2,1,1,1,2,1,1,1,2), dim=c(3,3))


> U <- svd(A)$u
> V <- svd(A)$v
> D <- diag(sqrt(svd(A)$d))
> B <- U %*% D %*% t(V)

# A

> A

# A
[,1] [,2] [,3]

[1,]

[2,]

[3,]

2
# B

> B
[,1]

[,2]

[,3]

[1,] 1.3333333 0.3333333 0.3333333


[2,] 0.3333333 1.3333333 0.3333333
[3,] 0.3333333 0.3333333 1.3333333
# A

> B%*%B
[,1] [,2] [,3]
[1,]

[2,]

[3,]

5.5.5
A 2 A2 2 A%*%A
A An A A = V %% D %% t(V)

An = V %% (Dn) %% t(V)
D Dn D n
matpow() *4

> matpow <- function(x, pow=2) {


+

y <- eigen(x)

y$vectors %*% diag( (y$values)^pow ) %*% t(y$vectors)

+ }
> matpow(diag(1:2))

# ((1, 0) , (0, 2)) 2

[,1] [,2]
[1,]

[2,]

*4

matpow() RjpWiki

54

matexp()

> matexp <- function(x) {


+

y <- eigen(x)

y$vectors %*% diag( exp(y$values) ) %*% t(y$vectors)

+ }
> matexp(matrix(0, 2, 2))

[,1] [,2]
[1,]

[2,]

> matexp(diag(2))
[,1]

# exp(E) = ((e, 0) , (0, e))


[,2]

[1,] 2.718282 0.000000


[2,] 0.000000 2.718282

5.6

5.6.1
dim ( ) 2
dim dim() nrow() ncol()

> x <- matrix(1:6, nrow=2, ncol=3)

# 2 * 3

> dim(x)

# dim

[1] 2 3
# dim(x)[1]

> nrow(x)
[1] 2

# dim(x)[2]

> ncol(x)
[1] 3

matrix() dim

dim matrix()
> x <- matrix(1:6, nrow=2, ncol=3)

# 2 * 3

> dim(x) <- c(3, 2)

# 3 * 2

> matrix(as.vector(x), nrow=2, ncol=6)

# 2 * 6

[,1] [,2] [,3] [,4] [,5] [,6]


[1,]

[2,]

6
# matrix() 1

> matrix(x, nrow=2, ncol=6)


[,1] [,2] [,3] [,4] [,5] [,6]
[1,]

[2,]

#
# as.vector()

55

5.6.2
matrix() nrow ncol
matrix()

> x <- matrix(1:6, nrow=3)

# ncol = 2

> y <- matrix(1:6, ncol=2)

# nrow = 3

> matrix(1, nrow=2, ncol=3)


[,1] [,2] [,3]
[1,]

[2,]

> matrix(1:2, nrow=2, ncol=3)


[,1] [,2] [,3]
[1,]

[2,]

> matrix(1:3, nrow=2, ncol=3, byrow=T)


[,1] [,2] [,3]
[1,]

[2,]

nrow ncol row() col()

> x <- matrix(1:6, nrow=2, ncol=3)

# 2 * 3

> row(x)

[,1] [,2] [,3]


[1,]

[2,]

2
#

> col(x)
[,1] [,2] [,3]
[1,]

[2,]

> ( x <- matrix(1:12, nrow=3, ncol=4) )

# 3 * 4

[,1] [,2] [,3] [,4]


[1,]

10

[2,]

11

[3,]

12

> x[1:2, 3:4] <- c(333, 555, 777, 999)

# 2 * 2

56

> x
[,1] [,2] [,3] [,4]
[1,]

333

777

[2,]

555

999

[3,]

12

which() arr.ind=TRUE
arr.ind=FALSE 2

> ( x <- matrix(1:6, nrow=2, ncol=3) )


[,1] [,2] [,3]
[1,]

[2,]

> ( y <- which(x%%2==0, arr.ind=TRUE) )


row col
[1,]

[2,]

[3,]

> ( x <- matrix(1:4, 2, 2) )


[,1] [,2]
[1,]

[2,]

4
# 2 x

> x[x%%2==0]
[1] 2 4
> x[x%%2==0] <- 0

# 2 x 0

> x
[,1] [,2]
[1,]

[2,]

5.6.3
apply(X, MARGIN, , ...) ()
MARGIN

MARGIN = 1 MARGIN = 2 MARGIN = c(1,2)

> ( x <- matrix(1:4, 2, 2) )


[,1] [,2]
[1,]

[2,]

> apply(x, 1, sum)


[1] 4 6

# -> rowSums(x)

57

mean sum

mean(x[i, ])

mean(x[, i])

mean(x[ , ])

apply(x, 1, sum)

colSums(x)

apply(x, 2, sum)

rowSums(x)

5.6.4
order()
max.col()

> ( x <- matrix(runif(4), 2, 2) )


[,1]

[,2]

[1,] 0.9542167 0.7191234


[2,] 0.8059257 0.0016700
# 2

> order(x[,2])
[1] 2 1

# 2

> x[order(x[,2]),]
[,1]

[,2]

[1,] 0.8059257 0.0016700


[2,] 0.9542167 0.7191234
# 1

> x[,order(x[1,])]
[,1]

[,2]

[1,] 0.7191234 0.9542167


[2,] 0.0016700 0.8059257

5.6.5
image()

> x <- matrix(rep(0:1,81), 9, 9)

0.0

0.2

0.4

0.6

0.8

1.0

> image(x, col=c(0,9))

0.0

5.1

0.2

0.4

0.6

0.8

1.0

58

6.1
2 3 4 ...

(2) array(, )
+

(1)

array() dim k
k dim()

> ( x <- array(1:8, dim=c(1, 4, 2)) )

# 3

, , 1
[,1] [,2] [,3] [,4]
[1,]

, , 2
[,1] [,2] [,3] [,4]
[1,]

8
# x[1 2 ]

> x[1, 4, ]
[1] 4 8

57 3 x i mean(x[i,i, ])

> x <- array(1:16, dim=c(2, 4, 2))


> apply(x, c(1,2), mean)
[,1] [,2] [,3] [,4]
[1,]

11

[2,]

10

12

59

aperm() perm () c(2,1)

> x

# 4

<- array(1:24, 2:4)

> xt <- aperm(x, perm=c(2,1,3))

# xt x

6.2
R 1 a 1
1 1
list()

> ( x <- list(1:5, list("Its my list.", c(T, F, T))) )


# 1

[[1]]
[1] 1 2 3 4 5

# 2 1

[[2]]
[[2]][[1]]
[1] "Its my list."

# 2 2

[[2]][[2]]
[1]

TRUE FALSE

TRUE

length(x)

x < as.list(NULL)

x[1]

x 1

x[1:2]

1 2

x[-1]

x[c(T,F,T)]

1 3

x[[1]]

x 1

x[2] < 10

2 10

x[[2]] < 10

2 10

x[3] < list(NULL)

3 NULL

x[3] < NULL

[[ ]] [ ]

*1
[ ]

> x <- list(1:3, 4:6, 7:9)


> x[1]

[[1]]
[1] 1 2 3

*1

[[ ]]
[ ]

60

> x[[1]]
[1] 1 2 3
> x[1:2]

# 1 2

[[1]]

# () x[[1:2]] x[[1]][[2]] ()

[1] 1 2 3
[[2]]
[1] 4 5 6
c() append()

# append(list(1:5), list(c(T, F, T)))

> c( list(1:5), list(c(T,F,T)) )


[[1]]
[1] 1 2 3 4 5
[[2]]
[1]

TRUE FALSE

TRUE

> rep(list(1:5, "Its my list."), 2)

# rep()

1 unlist()
split()

> ( x <- split(1:10, rep(c("odd", "even"), 5)) )


$even
[1]

8 10

$odd
[1] 1 3 5 7 9
> unlist(x)
even1 even2 even3 even4 even5
2

odd1

odd2

odd3

odd4

odd5

10

6.3 apply()
apply() apply(), mapply(), lapply(), sapply(), tapply()
m n X
1 R (for while) X < X+1

apply() C JAVA
apply()

apply(X, MARGIN, , ...)

MARGIN
MARGIN = 1 MARGIN = 2
MARGIN = c(1,2)

lapply(X, , ...)
sapply(X, , ...)

lapply() sapply() names


names

61

tapply(X, INDEX, , ...)

INDEX X
()

mapply( F , x, y, z, ... )

sapply() x, y, z,
F(x, y, z, ...) mapply(sum, 1:3, 4:6)
[ sum(1,4), sum(2,5), sum(3,6) ] = [ 5, 7, 9 ] mapply(sum, 1:3,

4:5) [ sum(1,4), sum(2,5), sum(3,4) ] = [ 5, 7, 7 ] (


warning

sweep(X, MARGIN, ,

MARGIN

FUN=, ...)

scale() FUN=+

apply() sweep()

> ( x <- matrix(1:8, ncol=4) )


[,1] [,2] [,3] [,4]
[1,]

[2,]

8
#

> apply(x, 2, sum)


[1]

7 11 15
#

> apply(x, c(1,2), sqrt)


[,1]

[,2]

[,3]

[,4]

[1,] 1.000000 1.732051 2.236068 2.645751


[2,] 1.414214 2.000000 2.449490 2.828427
> sweep(x, 1, apply(x,1,mean))

[,1] [,2] [,3] [,4]


[1,]

-3

-1

[2,]

-3

-1

> sweep(a, 2, apply(a,2,mean))

lapply()sapply() lapply()
sapply()
*2

> x <- list(a = 1:10, beta = exp(-3:3), logic = c(T,F,F,T))


> lapply(x, mean)

$a

# 1

[1] 5.5
$beta

# 2

[1] 4.535125
$logic

# (TRUE=1, FALSE=0)

[1] 0.5

*2

sapply() 2 sapply() replicate()

62

> sapply(x, mean)


a

beta

logic

5.500000 4.535125 0.500000


> lapply(x, quantile, probs = 1:3/4)

> sapply(x, quantile)

tapply()

> data(warpbreaks)

# 1

> attach(warpbreaks)

> fc <- factor(tension)

> levels(fc)

[1] "L" "M" "H"


# breaks

> tapply(breaks, fc, mean)


L

36.38889 26.38889 21.66667


mapply()

> mapply(rep, 1:3, 3:1)

# rep(1,3), rep(2,2), rep(3,1)

> mapply(rep, 1:3, 3:1)

# rep(3,1), rep(2,2), rep(1,3)

6.4
paste()

mode()

is.numeric()

is.integer()

is.complex()

is.character()

is.logical()

storage.mode()

as.numeric()

as.integer()

as.complex()

as.character()

as.logical()

> x <- c(1, 0, 1, 0, 1)


> mode(x)
[1] "numeric"
> mode(x) <- "complex"

# storage.mode(x) <- "complex"

> x
[1] 1+0i 0+0i 1+0i 0+0i 1+0i
> mode(x) <- "logical"
> x
[1]

TRUE FALSE

TRUE FALSE

TRUE

character > complex > numeric > logical > NULL

63

*3

TRUE 1 ,

FALSE 0

0 TRUE
*4

0 TRUE ,

0 FALSE

is.array() 2 is.array() TRUE

is.vector()

is.matrix()

is.array()

is.list()

is.data.frame()

is.factor()

is.ordered()

as.vector()

as.matrix()

as.array()

as.list()

as.data.frame()

as.factor()

as.ordered()

> x <- c(1, 0, 1, 0, 1, 0)

# x

> is.list(x)

[1] FALSE
> x <- as.list(x)

# x

> is.list(x)

# x ...

[1] TRUE
#

> is.vector(x)
[1] TRUE

as.character() as.numeric() NULL 0

6.5 names
names

mydata myname mydata name

names

> mydata <- c(57, 173, 19)

# BMI

> myname <- c("weight", "height", "BMI")

> names(mydata) <- myname

> mydata

# mydata

weight height
57

*3
*4

173

BMI
19

if (2.718) TRUE if

64

names
> mydata["BMI"]
BMI
19
> mydata["BMI"][[1]]
[1] 19
2

names names

> x <- list(57, "173", c(1,9,0,4,5,0,7))

# BMI

> names(x) <- c("weight", "height", "BMI")

> x
$weight
[1] 57
$height
[1] "173"
$BMI
[1] 1 9 0 4 5 0 7
# ( x[["weight"]] )

> x$weight
[1] 57
[[ ]] $
> temp <- "height"

# temp "height"

> x[[temp]]

# [[ ]]

[1] "173"

# x[["height"]]

> x$temp

# $

NULL

# x$temp NULL

> list(sequence=1:5, "letters"="abc")


$sequence
[1] 1 2 3 4 5
$letters
[1] "abc"
4

names

> x <- matrix(1:6, nrow=2, ncol=3)

# 2 * 3

> rownames(x) <- c("up", "down")

> colnames(x) <- c("left", "center", "right")

> x
left center right
up

down

65

> x["up","right"]
[1] 5

dimnames dimnames

> a <- matrix(1:6, nrow=2, ncol=3)


> dimnames(a) <- list(c("row1","row2"), c("col1","col2","col3"))
> a
col1 col2 col3
row1

row2

dimnames NULL
dimnames

> rownames(x) <- NULL

> colnames(x) <- NULL

> dimnames(x) <- NULL

> x <- 1:3


> y <- 4:6
> matname <- c("x", "y")

# x, y

> sapply(matname, get)

# x, y ()

x y
[1,] 1 4
[2,] 2 5
[3,] 3 6
5

dimnames names k

dimnames k NULL

> a <- array(1:16, dim=c(2, 4, 2))


> dimnames(a) <- list(NULL, c("A", "B", "C", "D"), c("a", "b"))
> a
, , a
A B C D
[1,] 1 3 5 7
[2,] 2 4 6 8
, , b
A
[1,]

9 11 13 15

[2,] 10 12 14 16

66

dimnames NULL

dimnames

> dimnames(a) <- list(c("row1","row2"), NULL)

> dimnames(a) <- NULL

R (attribute) mode length

2 ( names )
mode length names ( factor ) levels dim
mode length attributes()
mode as. () attr()
x dim x 2 2

> x <- 1:4


> mode(x)

# x

> attributes(x)

# mode length

> attr(x, "dim") <- c(2,2)

III

68

7.1
R date()

> date()
[1] "Mon Jul 21 16:31:52 2003"
log(x) x x

> x <- 10

# x 10

> log(x)

# x log10(x)

[1] 2.302585
2

> x <- 10

# x 10

> log(x, base=10)

# base 10

[1] 1

7.1.1
log()
base e

> log(x, base = exp(1))


base

> x <- 10
> log(x, 10)

# log(x, base=10)

69

> x <- 10
> log(base=2.718281828, x)
[1] 1

> x <- 10

###

> log(x)

###

> log(x <- 10)

7.1.2

order() *1

> order
*2 methods() getS3method()

# methods

> methods(mean)
[1] mean.data.frame mean.Date
[3] mean.default

mean.difftime

[5] mean.POSIXct

mean.POSIXlt

# default

> getS3method("mean", "default")

# default method

function (x, trim = 0, na.rm = FALSE, ...)

# mean

{
...

()

7.1.3
{ } *3 { }

1
1 2
*4

>

x <- 2 ; y <- 50

z <- 10

log(x*y, base=z)

*1

R

*3
*4 C JAVA
*2

70

[1] 2

7.1.4
)

<- function( 1, , n ) {

<>
}
+

rm()

> myfunc <- function(x) ifelse(x > 0, 1, -1)

> sin <- function(x) ifelse(x > 0, 1, -1)

> myfunc(1)

> sin(1)

[1] 1

[1] 1

> myfunc(-2)

> rm(sin)

[1] -1

> sin(1)

#
#

[1] 0.841471

7.2
7.2.1
== = ( = )

ASCII

==

!=

>=

>

<=

<

>

is.nan()

is.null()

is.finite()

<

is.na()

is.infinite()

complete.cases()

NA

NaN

NULL

x == y , x != y x, y
identical()

all.equal()

# R 1 1.0

> identical(1, 1.)


[1] TRUE
> identical(1, as.integer(1))

# as.integer(1) FALSE

[1] FALSE
> x <- 1;

y <- 1.0;

z <- 1.00000001;

> if (x == y)

+ identical(all.equal(x, z), TRUE)

[1] TRUE

71

7.2.2

&&

&

||

xor(x, y)

( )

> x <- 7
# 2 4

> (x > 2) && (x < 4)


[1] FALSE

# 2 8 ...

> if ( (x > 2) || (x < 8) ) print("True.")


[1] "True."

7.2.3
*5 ( )
$ [[ ]] mylist$element , mylist[[1]]
[ ] x[2]

[ [[

, **

()
1

% %%% , %in%
/

< > <= >=


== !=
!
&|&&||
<<

< , >

7.3
7.3.1 if else
if else TRUE FALSE

*5

RjpWikiisac S version 4

72

x <- 2
if (x > 0) {

# if ( )
#

TRUE

x <- -x

FALSE

sum(1:x)

sum(1:x)

} else {

}
if else 34 } else

56 R if () { }

else if else

R if
else

> a <- rnorm(1)

> {

> if (a >= 0) {

if (a == 0) b <- "zero"

if (a == 0) b <- "zero"

else b <- a

else b <- a

+ }
+ else b <- -a

if (a >= 0) {

else b <- -a

+ }

> myfunc <- function(a) {


+

if (a >= 0) {

if (a == 0) b <- "zero"

else b <- a

else b <- -a

return(c(a,b))

#
#

+ }
2

R 0 TRUE if (3.14) TRUE

if if x < 2
0 if TRUE

> x <- -3
> if (x<-2) print(x)

# x<-2 x -2

[1] 2

# 0 TRUE

()

73

if else

> if (a < 0) {
+

> myfunc <- function(a) {

print(0)

if (a < 0)

+ } else if (a < 1) {

else if (a < 1) print(1)

else print(2)

print(1)

+ } else print(2)

print(0)

+ }

ifelse(, 1, 2)

> x <- c(-2:3)


> sqrt(x)
[1]

NaN

NaN 0.000000 1.000000 1.414214 1.732051

NaN in: sqrt(x)


> sqrt(ifelse(x >= 0, x, NA))
[1]

NA

NA 0.000000 1.000000 1.414214 1.732051

7.3.2 switch
1 2 3

switch switch
switch
1 ... n NULL

> a <- 1

> a <- 2

+ switch(a,

# switch(,

"1" = print("one"),

"2" = print("two"),

print("?")

+ )

+ switch(a,

# switch(,

"1"

print("one"),

"2"

print("two")

+ )

[1] "two"

[1] "one"

7.3.3 && ||
2 && () || ()

> a <- 2

> a <- 2

> b <- -3

> b <- -3

> if ((a > 0) && (b > 0)) {

> if ((a < 0) || (b < 0)) {

c <- a*b

c <- -a*b

+ } else c <- -a*b

+ } else c <- a*b

> c

> c

[1] 6

[1] 6

74

7.4
7.4.1 for
for for ( in )
for

for *6
)

x 1 5

> x <- 0
> for (i in 1:5) {

# for ( in )

x <- x + 1

+ }
> x
[1] 5
+

for for

x i x 1 5

> x <- 1:5

> x <- 1:5

> for (i in x) x <- append(x, i)

> for (i in 1:5) x <- append(x, i)

> x

> x

[1] 1 2 3 4 5 1 2 3 4 5
2

[1] 1 2 3 4 5 1 2 3 4 5

for

plot() plot()

> x <- 0

> par(mfrow=c(2,2))

> y <- matrix(1:10, 2, 5)

> x <- list(1:6, sin, runif(6), dnorm)

> for (i in y) x <- x+1

> for (i in x) {

> x

[1] 10

+ }

plot(i, xlim=c(0,2*pi))

7.4.2 while
while
TRUE
x 1 5

*6

75

> x <- 0
> while (x <= 5) {

# while ( )

# TRUE

x <- x + 1

# FALSE 1

+ }
> x
[1] 6

7.4.3 break
break for while *7 next for while
*8

> x <- 0

> x <- 0

> for (i in 1:5) {

> for (i in 1:5) {

x <- x + 1

next

# x 1

if (x == 3) break

# x 3

x <- x + 1

# for

+ }

+ }
> x

> x

[1] 3

[1] 0

7.4.4 repeat
repeat break
> x <- 0
> repeat {
+

if (x <= 5) x <- x+1

# break

else

# x > 5 repeat

break

+ }
> x
[1] 6

7.5
7.5.1
2 mydouble()

> mydouble <- function(x) 2*x


> mydouble <- function(x) {
+

return( 2*x )

+ }
> mydouble(2)
[1] 4
*7
*8

break
next

76

7.5.2
R %+=% %=%

> "%+=%" <- function(x, y) x <<- x + y


> "%-=%" <- function(x, y) x <<- x - y
> x <- 1;
> (x %+=% 2)
[1] 3
> (x %-=% 3)
[1] 0

7.5.3
R
return() return()
return()

2 mydouble()

NA return()
return()

> mydouble <- function(x) {

> mydouble <- function(x) {

if (!is.numeric(x)) return(NA)

if (!is.numeric(x)) return(NA)

return(2*x)

2*x

+ }

+ }

return()

return()
*9

> mydouble <- function(x) {

> mydouble <- function(x) {

y <- 2*x

y <- 2*x

return(x, y)

return( list(x, y) )

+ }

+ }

> mydouble(2)

> mydouble(2)

$x

[[1]]

[1] 2

[1] 2

$y

[[2]]

[1] 4

[1] 4

...

*9

> mydouble <- function(x) return( list(input=x, output=2*x) )

77

> mymultiply <- function(x) {


+

return( function (y){ x*y } )

+ }
> result <- mymultiply(2)

# result(y) 2*x

> result(3)
[1] 6

7.5.4
invisible()

> mydouble <- function(x) {


+

return( invisible(2*x) )

+ }
> mydouble(3)

> y <- mydouble(3)

> y
[1] 6

7.5.5
stop()
warning()

> mydouble <- function(x) {

> mydouble <- function(x) {

if (!is.numeric(x)) {

stop("not numeric !")

if (!is.numeric(x)) {

warning("not numeric !")


return(NA)

return(2*x)

+ }

return(2*x)

> mydouble("a")

+ }

mydouble("a") : not numeric !

> mydouble("a")
[1] NA
not numeric ! in: mydouble("a")

7.5.6

try() mydouble() try()


mydouble()

> mydouble <- function(x) {


+

if (x%%2 == 0) stop("error !")

return(2*x)

# 2*x

+ }
> result <- lapply(1:3, function(x){ try(mydouble(x), TRUE) } )

78

> result

7.5.7 <<

< <

*10

> x <- 10

# x

> myfunc <- function(y) {

# y

x <- y + 999

# x myfunc()

return(x)

+ }

> x
# x 10

[1] 10
> myfunc(1)
[1] 1000

# x

> x

[1] 10
<< <<

> x <- 10

# x

> myfunc <- function () {


+

x <- 777

# myfunc() x

x <<- 99

# x 99

print(x)

# x

+ }
> myfunc()
[1] 777

# myfunc() ( x )

> x

# myfunc() x

[1] 99

# x 99

x
x

assign(, , env=.GlobalEnv)
*10

> myfunc <- function() print(z)


> myfunc()
print(z) :
> z <- 999
> myfunc()
[1] 999

# z
# z
"z"
# z 999
# myfunc()
# z 999

R R RjpWiki

79

> x <- 10

> x <- 10

> myfunc <- function () {

> myfunc <- function () {

x <- c(1, 2)

x <- 1:3

x[2] <<- 0

assign(x[2], 2, env=.GlobalEnv)

print(x)

print(x)

+ }

+ }

> myfunc()

> myfunc()

[1] 1 2 3

assign(x[2], 2, env = .GlobalEnv) :

> x

[1] 10

# ...

7.5.8

> myfunc <- function(x) {


+

y <- 2

mydouble <- function(a, b) {

a*b

mydouble(x, y)

+ }
> myfunc(3)
[1] 6

7.5.9

formals() alist()

> f <- function(x) 2*x

> f

function(x) 2*x

# body(f)

> formals(f)

# f

$x
> formals(f) <- alist(x=, y=3)

# x, y y 3

> f

# f

function (x, y = 3)
2*x
> formals(f) <- alist(x = , y = 3, ... = )
> f
function (x, y = 3, ...)
2*x

# ...

80

7.5.10



on.exit()
on.exit()

> myfunc <- function(x) {

> myfunc <- function(x) {


+

oldpar <- par()

par(col="red")

on.exit(par(oldpar))

plot(x)

par(col="red")

par(oldpar)

plot(x)

oldpar <- par()

+ }

+ }

> myfunc(1:10)

> myfunc(1:10)

on.exit() on.exit()
on.exit() add add=Tadd=F
on.exit(par(oldpar), add=T)

# par(oldpar)

on.exit(par(oldpar), add=F)

# par(oldpar)

on.exit()

7.6
7.6.1
if *11
myprod() n 0 1 ifelse()

> myprod <- function(n) {

> myprod <- function (n) {

if (n==0) 1

else

+ }

prod(1:n)

ifelse(n==0, 1, prod(1:n))

+ }

> myprod(0)

> myprod(0)

[1] 1

[1] 1

> myprod(5)

> myprod(5)

[1] 120

[1] 120

7.6.2

*11

76

81

y y 1

> mymultiply <- function(x, y=1) {

> mymultiply <- function(x, y=x^2) {

return(x*y)

return(x*y)

+ }

+ }

> mymultiply(2,5)

> mymultiply(2,5)

[1] 10

[1] 10

> mymultiply(2)

> mymultiply(2)

[1] 2

[1] 8

> myfunc <- function(x=2*y, y=x^2) {


+

return(x*y)

+ }
> myfunc(2)
[1] 8
> myfunc()
myfunc() :

missing()
missing()
missing() TRUE *12 missing()
y missing()
warning()

> mymultiply <- function(x, y) {

> mymultiply <- function(x, y=1) {

if (missing(y)) return(x)

if (missing(y)) warning("y isnt inputted.")

else return(x*y)

return(x*y)

+ }

+ }

> mymultiply(2,5)

> mymultiply(3,2)

[1] 10

[1] 6

> mymultiply(2)

> mymultiply(2)

[1] 2

[1] 2
y isnt inputted. in: mymultiply(2)

7.6.3
c() 2 10
... ...
... =

*12

missing(y) y y < match.arg() FALSE

82

> f <- function(x, ...) {

> g <- function(...) {

> h <- function(... , y=1) {

args <- list(...)

return(args)

+ }

label <- deparse(

substitute(x)

plot(x, xlab=label, ...)

+ }

+ }

> h(5)

> f(1:6, "title")

[1] 2

[[1]]

> h(5,y=2)

[1]

> x <- 1:10


> f(x, ylab="y")

2*y

[1] 4

[[2]]

> h(y=2)

[1] "title"

[1] 4

7.6.4
apply() R
*13

> f <- function(x, Fun) Fun(x)

> apply(matrix(1:4,2),1,function(x) { 2*x } )

> f(3, sqrt)

[,1] [,2]
[1,]

[1] 1.732051

[2,]

> g <- function(x, Fun=sqrt) Fun(x)


> g(5)
[1] 2.236068

apply()

> x <- c(1, 4, 9, 16, 25, 36)

> mean(x)

> f <- function(x, Fun) Fun(x)

[1] 15.16667

> f(x, F=function(z) {2*z})

> F <- function(x, a=0)

[1]

> g <- function(x, a, fun) fun(x, a)

8 18 32 50 72

mean(x, a)

> g(x, 0.4, F)


[1] 12.5

7.6.5

xl

xlab xlim
> plot(sin, xlab = "x-title")

# x

> plot(sin, xla

= "x-title")

# "xla" "xlab"

> plot(sin, xl

= "x-title")

# "xl" "xlab"

Error in if (from == to || length.out < 2) by <- 1 :


missing value where TRUE/FALSE needed
match.arg() (
*13

RjpWiki

83

> myfunc <- function(a, b, do = c("sum", "minus", "multi", "div")) {


+

do <- match.arg(do)

switch(do, sum

= a+b,

minus = a-b,

multi = a*b,

div

# do (match.arg )
#

= a/b)

+ }
> myfunc(3, 2, "minus")
[1] 1
# "mi" "minus"

> myfunc(3, 2, "mi")


[1] 1

# "m" "minus" ...

> myfunc(3, 2, "m")

Error in match.arg(do) : ARG should be one of sum, minus, mult, div

7.7

Recall()
Recall()

> myfactorial <- function(n) {

> myfactorial <- function(n) {

if (n <= 1) return(1)

if (n <= 1) return(1)

else

else

return( n * myfactorial(n-1) )

return( n * Recall(n-1) )

+ }

+ }

> myfactorial(5)

> myfactorial(10)

[1] 120

[1] 3628800

7.8

cat() print()

myfunc() x y s

> myfunc <- function(z) {


+

x <- rnorm(1);

cat("x =", x, "\n"); cat("y =", y, "\n")

ifelse( ((x < 0) || (y < 0)), s <- -x*y, s <- x*y )

cat("s =", s, "\n")

return(s*z)

+ }

y <- rnorm(1)
# x y
# s

84

> myfunc(5)
x = 1.305908
y = -0.1477835
s = 0.1929916
[1] 0.9649579
R

browser()

nls()

wherereturn()
Q

debug()

browser()
undebug()

trace()

untrace()

traceback()

debugger()

try()

stopifnot()

system.time()

Sys.sleep()

browser()

> myfunc <- function(z) {


+

x <- rnorm(1);

y <- rnorm(1)

ifelse( ((x < 0) || (y < 0)), s <- -x*y, s <- x*y )

browser()

return(s*z)

+ }
> myfunc(5)
Called from: myfunc(5)
Browse[1]> ls()

[1] "s" "x" "y" "z"


Browse[1]> x

# x

[1] -0.3039924
Browse[1]> c

[1] 0.6327254

7.9
7.9.1
C x[1]x[2] R

assign() paste()

85

# Ai i

> for (i in 1:5) assign(paste("A", i, sep=""), i)


> A5
[1] 5

7.9.2 readline()
readline()
*14
Sys.sleep(time)

> mytest <- function() {

> mymessage <- function() {

ANS <- readline("1+2? ")

Sys.sleep(3)

if (ANS == "3") cat("Correct!\n")

cat("Hello.\n")

else

+ }

cat("Wrong...\n")

+ }

> mymessage()

> mytest()

Hello.

1+2? 3
Correct!
readline()
strsplit() unlist()
as.numeric() , myfunc()

> myfunc <- function () {

> x <- 1:5

Str <- readline("Enter : ")

> y <- get(readline())

as.numeric(unlist(strsplit(Str, ",")))

+ }
> x <- myfunc()

> y
[1]

Enter : 1,2,3,4,5
> x
[1] 1 2 3 4 5

7.9.3 menu()
menu() choices , title
0, 1, 2, ..0
switch

> switch(menu(c("1+2", "3*4"), title="0: exit") + 1, cat("Nothing done\n"), 3, 12)


0: exit
1: 1+2
2: 3*4
1

[1] 3

*14

RjpWiki

86

8.0
R 10 2
round()

> 0.4-0.2-0.2
[1] 0

> 0.4-0.3-0.1
[1] 2.775558e-17
> round( 0.4-0.3-0.1 )

# round()

[1] 0

8.1
R

round(x, digits = 0)

IEEE digits = 0

ceiling(x)

floor(x)

signif(x, digits = 6)

digits ( 6 )

trunc(x)

x 0

round() IEEE

*1

(1) 1

(2) 2
(3) 1
+

(2)

*1

RjpWiki ()

87

(3) 2.45 2 2.5

round(2.4)

round(2.5)

round(3.5)

round(2.51)

round(3.51)

round(3.46)

(1)

(2)

(2)

(1)

(1)

(1) (3)

8.2

beta(a, b)

B(a,b) = (gamma(a)gamma(b)) / gamma(a+b) a,b

lbeta(a, b)

log(beta(a,b))

gamma(x)

x n
n! gamma(n+1)

lgamma(x)

log(gamma(x))

digamma(x)

lgamma

trigamma(x)

lgamma

tetragamma(x)

lgamma

pentagamma(x)

lgamma

choose(n, k)

(n k )gamma(n+1) / ( gamma(k+1)gamma(n-

k+1) ) n, k

lchoose(n, k)

choose(n,k) log(choose(n,k))

(s) =

xs1 ex dx

1 (1) = 1
+

1
2 ( ) =
+

3 (s) = (s 1)(s 1)
+
4 (n) = (n 1)!
+

(s > 1)

(n : )

n! gamma(n+1) *2 factorial()
3!

> factorial(3)
[1] 6

*2

prod() 0! = 1
lgamma(n+1) lfactorial(n)

88

8.3
x nu

besselI(x, nu, expon.scaled=F)

besselK(x, nu, expon.scaled=F)

besselJ(x, nu)

besselY(x, nu)

gammaCody(x)

gamma() gamma()

8.4
x f (x) f (x) = 0

f (x)

O
x
x

R uniroot() 0 x 2 f (x) = x3 2 0 x

> f <- function (x) x^3 - 2

# (1) f(x)

> uniroot(f, c(0, 2))

# (2) c(0, 2)

$root

# $root

[1] 1.259934
()
x = 0.6931457

8.5
polyroot() p(x) = 5 + 4x + x2 c(5,

4, 1)
> polyroot(c(5, 4, 1))

# x^2 + 4x + 5 = 0

[1] -2+1i -2-1i


> polyroot(c(1, 2, 1))

# x^2 + 2x + 1 = 0

[1] -1-1.665335e-16i -1+1.665335e-16i

round()

> round( polyroot(c(1, 2, 1)), digits=3 )


[1] -1+0i -1+0i

# x^2 + 2x + 1 = 0

89

8.6
R

> f <- expression( a*x^4 )

# (1) f expression()

> D(f, "x")

# (2) D(f, )

a * (4 * x^3)
DD

> DD <- function(expr, name, order = 1) {


+

if(order < 1) stop("order must be >= 1")

if(order == 1) D(expr, name)

else DD(D(expr, name), name, order - 1)

+ }
# D(, , )

> DD(f, "x", 3)


a * (4 * (3 * (2 * x)))

deriv()

> g <- deriv(~ exp(-x^2), "x", func=T)

# (1) f = exp(-x^2) g

> g(2)

# (2) g(2)

[1] 0.01831564

f(2)

f(2)

attr(,"gradient")
x
[1,] -0.07326256
deriv() *3

f < deriv( x2, x, func=T)

x2 x f (x)

g < deriv( x2y, c(x,y), func = TRUE)

x2 y x y
g(x, y)

h < deriv( x2yz, c(x,y), function(x, y, z=4) )

x2 yz x
y
h(x, y, z = 4)

*3

deriv() hessian=T hessian deriv(... , hessian=T)


deriv3()

90

8.7
integrate()

f <- function(x) x^2

# (1)

integrate(f, 0, 1)

# (2) integrate(, , )

0.3333333 with absolute error < 3.7e-15

# 0.3333333

R
> integrate(sin, 0, pi)
2 with absolute error < 2.2e-14
Inf Inf()

1.96

# dnorm:

> integrate(dnorm, -Inf, 1.96)


0.9750021 with absolute error < 1.3e-06

adapt adapt(, lower=, upper=, functn=)


adapt() value relerr
eps

> library(adapt)
> mynorm <- function(z) {
+

(1/sqrt(2*pi))^length(z) * exp(-0.5 * sum(z * z))

+ }
> adapt(2, lo = c(-4,-4), up = c(4,4), functn = mynorm)
value

relerr

minpts

lenwrk

ifail

0.993709 0.0004751543

263

73

8.8
optim() control fnscale
( fnscale=1)
10 3 p

> LL < - function(p) choose(10,3)*p^(3)*(1-p)^(7)

> optim(c(0, 1), LL, control=list(fnscale=-1))

# (0, 1)

$par
[1] 0.30 0.95
$value

[1] 0.2668279

# 0.3

......................

91

8.9
nlm() *4
10 3 p

> LL <- function(p) -choose(10,3)*p^(3)*(1-p)^(7)

> nlm(LL, 0.5, fscale=-1)

# 0.5

$minimum
[1] -0.26683
$estimate

[1] 0.3

# 0.3

......................

8.10
lpSolve lp() f.conx1 + 2x2 + 3x3

9, 3x1 + 2x2 + 2x3 15 f.objx1 + 9x2 + x3


> library(lpSolve)
> f.obj <- c(1, 9, 3)
> f.con <- matrix (c(1, 2, 3, 3, 2, 2), nrow=2, byrow=TRUE)
> f.dir <- c("<=", "<=")
> f.rhs <- c(9, 15)
> lp ("max", f.obj, f.con, f.dir, f.rhs)
Success: the objective function is 40.5
> lp ("max", f.obj, f.con, f.dir, f.rhs)$solution
[1] 0.0 4.5 0.0

> lp ("max", f.obj, f.con, f.dir, f.rhs, int.vec=1:3)


Success: the objective function is 37
> lp ("max", f.obj, f.con, f.dir, f.rhs, int.vec=1:3)$solution
[1] 1 4 0

8.11
fft() convolve(x,y) 2 *5

> x <- 1:4


> fft(x)
[1] 10+0i -2+2i -2+0i -2-2i
> fft(fft(x), inverse = TRUE)/length(x)
[1] 1+0i 2+0i 3+0i 4+0i

*4
*5

( )
mvfff()

IV

93

9.1
data.frame
1 2
*1

2
3
4
5

F
M

158
162
177

M
M

173
166

51
55
72
57
64

9.1.1

data.frame()

1 *2

> data.frame( 1 = 1, 2 = 2, ... )


+
data.frame()

*1

*
,

*2 x data.frame(x)

94

> sex <- c("F","F","M","M","M")


> height <- c(158,162,177,173,166)

SEX HEIGHT WEIGHT

158

51

162

55

177

72

173

57

5
+

166

64

> weight <- c(51,55,72,57,64)


> ( x <- data.frame(SEX=sex, HEIGHT=height, WEIGHT=weight) )

x
x x
$

# x

> x$HEIGHT
[1] 158 162 177 173 166

# x

> mean( x$WEIGHT )


[1] 59.8

# x 2

> x[,2]
[1] 158 162 177 173 166

9.1.2

summary()
1 3

> summary(x)
SEX

HEIGHT
:158.0

WEIGHT

F:2

Min.

M:3

1st Qu.:162.0

1st Qu.:55.0

Median :166.0

Median :57.0

Mean

Mean

:167.2

Min.

:51.0

:59.8

3rd Qu.:173.0

3rd Qu.:64.0

Max.

Max.

:177.0

:72.0

9.2
5 sexheightweight

sex

height

weight

158

51

162

55

177

72

173

57

166

64

9.2.0

22

95

9.2.1

x < read.table(C:/data.txt)

(1) data01.txt read.table()


R

data01.txt
F

158

51

162

55

V2 V3

177

72

F 158 51

173

57

F 162 55

166

64

> ( x <- read.table("data01.txt") )


V1

...........
(2) data02.txt 1
read.table() header T

+
)

data02.txt

sex height weight

> ( x <- read.table("data02.txt", header=T) )


sex height weight

158

51

162

55

158

51

177

72

162

55

173

57

166

64

...................
(3) data03.txt 1 2
header T skip 1

> ( x <- read.table("data03.txt", header=T, skip=1) )

+
)

data03.txt

### data03.txt
F

158

51

158

51

162

55

162

55

177

72

177

72

173

57

166

64

(4) data04.txt
data04.txt
)
sep ,
sex,height,weight
Yt
F,158,51
> ( x <- read.table("data04.txt", header=T, sep=",") )
sex height weight

,
*

,
*

M,177,72

158

51

M,173,57

162

55

M,166,64
+

read.table() row.names col.names


*3

*3

F,162,55

...................

sex height weight

sex height weight

...................

rownames() colnames()

96

sep =

skip = 0

nrows = 1

header = F

F
comment.char

row.names=NULL

row.names=

row.names=

row.names=

read.table()

header

sep

quote

dec

read.csv()

read.csv2()

read.delim()

Yt

read.delim2()

Yt

read.fwf()

Yt

widths

data04.txt read.csv()

> x <- read.csv("data04.txt")


1

Windows

data
2

Windows R C:/data.txt C:Ydata.txt Y

YY Y

9.2.2 EXCEL
csv
read.csv() data04.txt EXCEL
[] [] [] [
] [CSV ] Windows R

97

9.1

9.2 csv

Mac OS X R

9.3

9.4 csv

EXCEL read.csv()
read.csv() header F col.names

data05.csv

F,158,51

F,162,55

> ( x <- read.csv("data05.csv", header=F,

M,177,72

M,173,57

col.names=c("SEX","HEIGHT","WEIGHT")) )
SEX HEIGHT WEIGHT

158

51

162

55

...................

EXCEL

M,166,64

EXCEL Windows Mac OS X

9.5 Windows

9.6 Mac OS X

98

(1) Windows *4
> x <- read.delim("clipboard")

> x <- read.delim("clipboard", header=F)


(2) Mac OS X
excel.mac <- function(...) {
args <- c(...)
temp <- matrix(scan(""), byrow=TRUE, ncol=length(args))
data <- data.frame(temp)
colnames(data) <- args
return(data)
}
excel.mac( 1, 2,) *4

> x <- excel.mac("X", "Y")


1:

"Enter $ 2

xls
gregmisc Perl*5 xls read.xls()
sheet

> library(gregmisc)
> x <- read.xls("data01.xls", sheet=1)

9.3
x *6

x$x[]x[[]]

SEX WEIGHT

x[2], x[[2]]

x[3, 2], x[[3, 2]]

3 2

x[[3, ]], x[[3, ]]

x[c(1, 2)]

1 2 x[ , c(1, 2)]

x[c(3, 4), ]

3 4

x[c(1,3,5,2,4), ]

c(1,3,5,2,4)

*4

R Editor
write.table(x, clipboard, sep=Yt) x EXCEL

*5 Windows ActivePerl
*6 [ ] names

99

x[ ,c(T,F,T)]

c(T,F,T) TRUE

x[x$SEX==F, ]

x[x$SEX==F & x$WEIGHT>50, ]

F 50kg

(1) x[[2]] x[2] 2

# 2 -> a[2]

> x[[2]]
[1] 158 162 177 173 166

# 1, 3, 4

> x[c(1,3,4),]
SEX HEIGHT WEIGHT
1

158

51

177

72

173

57

(2) NULL
> x[[2]] <- NULL

# 2 NULL x <- x[,-c(2)]

> x
SEX WEIGHT
1

51

55

72

57

64

9.4
x y

ncol(x)

nrow(x)

names(x)

rbind(x, y)

x y x y

cbind(x, y)

x y x y

data.frame(x, y)

x y x y

merge(x, y)

x y all=T
all=T

100

D1 D2

> id <- c("A","C","E");

height <- c(158,177,166)

D1
ID

*
)

ID

> D1 <- data.frame(ID=id, H=height)

A 158

A 51

>

C 177

B 55

> id <- c("A","B","D","E"); weight <- c( 51, 55, 57, 55)

E 166

D 57

> D2 <- data.frame(ID=id, W=weight)

D2

4 E 55
,
+

(1) 2 merge() merge() 2

ID all
ID T
all.x all.y

> merge(D1, D2)


ID

> ( D <- merge(D1, D2, all=T) )

ID

A 158 51

A 158 51

E 166 55

C 177 NA

E 166 55

NA 55

NA 57

(2) by 2 ID
2 by.x by.y *7
by by.x by.y merge(D1,

D2, by.x=names(D1), by.y=names(D2), all=T)

> ( merge(D1, D2, by="ID", all=T) )


ID

A 158 51

C 177 NA

3
4

> ( merge(D1, D3, by.x="ID",


+

by.y="Num", all=T) )

Num

A 51

A 158 51

B 55

E 166 55

C 177 NA

D 57

E 166 55

E 55

........

D3

NA 55

ID

........

(3) order()
(1) D W

> sortlist <- order(D$W)


> ( D4 <- D[sortlist,] )
ID

*7

A 158 51

E 166 55

NA 55

NA 57

C 177 NA

by.x sort F

101

()
> rownames(D4) <- c(1:nrow(D4))
> D4
ID

A 158 51

E 166 55

...........
order(1 , pmax(1 , 2 ))

> sortlist <- order(D$W, pmax(D$W, D$H))


# W

> D[sortlist,]
W

# W

A 158 51

# H

ID

> sortlist <- order(D$W, pmax(D$W, D$ID))


> D[sortlist,]
ID

A 158 51

E 166 55

NA 55

E 166 55

NA 57

C 177 NA

C 177 NA

# W
# W
# ID

NA 55
NA 57

9.5

head(x, n=a)

a tail(x, n=b) b

na.omit(x)

NA na.exclude()

transform(x, y=)

x y

x[sapply(x, )]

TRUE x[sapply(x,

is.numeric)]
subset(x, )

subset(x, id>3) id > 3

subset(x, , )

subset(x,

id>3, c(id,sex)) id > 3 id sex


split(x, )

split(x, x$w==70)

by(x, x$, mean)

x mean

aggregate()
reshape(x, ...)

DF

> id

<- c(

1,

2,

3,

4,

5)

# ID

DF
ID SEX

> sex <- c("F","F","M","M","M")

# (F:M:)

F 158 51

> h

<- c(158,162,177,173,166)

F 162 55

> w

<- c( 51, 55, 72, 57, 64)

M 177 72

> DF

<- data.frame(ID=id, SEX=sex, H=h, W=w)

M 173 57

5 5
+

M 166 64

102

(1) DF W
sum() gW 1000

> sum(DF$W)

> DF$W <- DF$W * 1000

# kg g

> DF
ID SEX

F 158 51000

F 162 55000

..................
DF G transform()
> transform(DF, G=DF$W * 1000 )
ID SEX

# DF$G <- DF$W * 1000

F 158 51 51000

F 162 55 55000

.....................
(2) ifelse(, TRUE , FALSE
)

> DF$W <- ifelse(DF$SEX=="F", NA, DF$W)

# (NA )

> DF
ID SEX

F 158 NA

F 162 NA

M 177 72

...............
(3) [ ]
> cond <- (DF$H >= 170)

# H 170cm

> DF[cond,]
ID SEX

M 177 72

M 173 57

subset() sapply()

> subset(DF, ID>3)


ID SEX

M 173 57

M 166 64

> subset(DF, ID>3, c(ID, SEX))


ID SEX
4

# ID > 3

# ID > 3 "ID" "SEX"

103

(4) as.factor() *8
> DF$ID <- as.factor(DF$ID)

> DF[sapply(DF, is.numeric)]

1 158 NA
2 162 NA
........
(5) ID SEX reshape()
> reshape(DF, timevar="SEX", idvar="ID", direction="wide")
ID H.F W.F H.M W.M
1

1 158

51

NA

NA

2 162

55

NA

NA

NA

NA 177

72

NA

NA 173

57

NA

NA 166

64

# H.FW.FH.MW.M

9.6
(1) edit() *9
> DF <- edit(DF)

9.7

Windows

9.8

Mac OS X

(2) 62
data.matrix()
str() is.data.frame()

*8

as.ordered(A$id) as.single(A$w)
data.entry(DF$ ID, DF$ SEX)
data.entry(..., Modes = NULL, Names = NULL) Modes Names

dataentry(data, modes) data modes (list() )

de(..., Modes = list(), Names = NULL) 2


*9

104

9.7
9.7.1
R data()
> data()

> data(package ="base")

# base

> data(USArrests, "VADeaths")

# USArrests, VADeaths

> help(USArrests)

# USArrests

> library(nls)

# nls

> data(Puromycin)

# Puromycin

9.7.2 attach() detach()


$ $

myframe myframe$u myframe$v myframe$w


attach(myframe) myframe$ uvw
u

> u <- 1:5;

v <- rnorm(5);

w <- u*v

> myframe <- data.frame(u=u, v=v, w=w)


> attach(myframe)
# attach() w

> w
[1]

0.166959

1.676896

1.435630 -3.024536

1.859002

attach() *10

> data(sleep)

# R (W.S.Gosset (Student) )

> attach(sleep)
# attach() extra

> extra
[1]
[13]

0.7 -1.6 -0.2 -1.2 -0.1

3.4

3.7

0.8

1.1

1.6

4.6

3.4

0.1 -0.1

4.4

5.5

0.0

2.0

1.9

0.8

detach() myframe$u
u attach

*10

attach(myframe)

> myframe <- list(c("a","b","c"), c(1:3), c(1.5,3.2,-0.8))


> names(myframe) <- c("u", "v", "w")
> attach(myframe)
# attach()
> u
# u
[1] "a" "b" "c"

105

detach() (on.exit(detach(sleep) )
)

> search()

> detach(sleep)

# sleep

attach() with() with()


attach() with()

> data(sleep)
# sleep F

> with(sleep, {
+

x <- extra[group==1];

y <- extra[group==2];

var.test(x, y)

+ })
F test to compare two variances

9.7.3 R
R ( SAS ) foreign
SPSS

> library(foreign)
> read.spss("datafile", use.value.labels=FALSE)
R foreign

lookup.xport()

SAS XPORT

read.dta()

Stata binary files

read.epiinfo()

Epi Info data files

read.mtp()

Minitab Portable Worksheet

read.spss()

SPSS data file

read.ssd()

read.xport() SAS

read.xport()

SAS XPORT format library (ver.6)

write.dta()

Stata binary format

gregmisc read.xls() EXCEL .xls


Windows R Perl ActiveStatehttp : //www.activestate.com/
ActivePerl 9.9 ActivePerl x.x.x.xxx 9.10 Download

106

9.9

9.10

"Next> $
Windows ActivePerl OS
2000/XP MSI 98/Me/NT 9.12
Windows Installer MSI

9.11

9.12

ActivePerl C:YperlYbinYperl.exe
read.xls() ActivePerl perl

9.7.4

NA NA
> sex <- c("F",NA,"M"); height <- c(158,162,NA); weight <- c(51,55,72)
> ( x <- data.frame(SEX=sex, HEIGHT=height, WEIGHT=weight) )
SEX HEIGHT WEIGHT
1

158

51

2 <NA>

162

55

NA

72

data06.txt

NA

107

> ( x <- read.table("data06.txt", header=T, sep=",") )


sex height weight

data06.txt

sex,height,weight

158

51

F,158,51

162

55

F,162,55

NA

72

M,

173

57

M,173,57

166

64

M,166,64
+

9.7.5 scan()

,72
,

scan()
scan() *11
data07.txt 6 1
x ()

> x <- scan("data07.txt", skip=1, nlines=6)


Read 20 items

# data.txt

> x
62.6

25.0

[13] 178.0
[19]

23.0

0.0 163.0
75.4

28.0

33.0

1.0 158.0

49.8

158 49.8 25 0

42.0

1.0

163 68.7 42 1

1.0 163.0

55.7

178 75.4 33 1

68.7

0.0

163 55.7 28 0
+

scan()

x <- matrix( scan("data07.txt", skip=1, nlines=6), 5, byrow=T)


list5 4
R

> x <- scan("data07.txt", list("",weight="","",sex=""),skip=1, nlines=6)


Read 5 records
> x
[[1]]
[1] "171" "158" "163" "178" "163"
$weight
[1] "62.6" "49.8" "68.7" "75.4" "55.7"
[[3]]
[1] "23" "25" "42" "33" "28"
$sex
[1] "1" "0" "1" "1" "0"

*11

171 62.6 23 1

[1] 171.0
[7]

data07.txt

R read.table() scan()
scan() scan()
read.table() write.table() write()

108

= 0 ( = 1 ) sex

> x <- scan("data07.txt", list(h=0,w=1,a=0,s=""), skip=1)


Read5 records
> x
$h
[1] 171 158 163 178 163
$w
[1] 62.6 49.8 68.7 75.4 55.7
$a
[1] 23 25 42 33 28
$s
[1] "1" "0" "1" "1" "0"
R sex
read.table()

edit()
> x$h <- x$h/100
scan() read.table()
read.table()

sep =

scan()

sep =

skip = 0

nrows = 1

header = F

skip = 0

nlines

what

nmax = 1

comment.char

nmax what

quote

row.names,

col.names

quote = n = 1na.strings
= NA

109

scan()
scan() 2 2

> x <- scan("data08.txt", sep=",")


Read 10 items

data08.txt

1,2,3,4,5

> x

6,7,8,9,10

[1]

9 10

data09.txt

> x <- scan("data09.txt", sep=",")


Read 11 items

data09.txt

1,2,3,4,5,

> x

6,7,8,9,10

[1]

5 NA

9 10

9.7.6

*
)

data10.txt

1,2,3,4,5,

6,7,8,9,10,
,
+


fill = TRUE


strip.write = TRUE

read.line() blank.lines.skip = FALSE


fill = TRUE

10

110

10

10.1
read.table() write.table() write() *1 5 3
data07.txt C:/ data.txt read.table()
write.table(, ) output.txt

write.table(x,C:/output.txt) quote=F
> x <- read.table("C:/data11.txt")
> write.table(x, "C:/output.txt", quote=F,
col.names=F, append=T)

data11.txt

0.9, 1.2, 1.9

1.3, 1.6, 2.7


2.0, 3.5, 3.7

# append=F

1.8, 4.0, 3.1


0.9, 1.2, 1.9
+

write.table() write(

, )

write(, , append = T, ncolumns = )

write.table(, , append=T, quote=F, col.names=F)


write()

> x <- matrix(1:8, ncol=2)

# 4 * 2

> write(x, file="data12.txt")

# data12.txt

> scan("data12.txt")

# scan ()

Read 8 items
[1] 1 2 3 4 5 6 7 8
> y <- matrix(scan("data12.txt"), ncol=4)

Read 8 items
> y
[,1] [,2] [,3] [,4]
[1,]

[2,]

*1

MASS write.matrix() write.table()

10

111

save()
load()

> save(x, file="data13.dat")


> rm(x)

# data13.dat

> load("data13.dat")

10.2
{

} write() 1

> x <- c(1:9)


> out <- NULL

data14.txt

1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9

> for (i in 1:(length(x)-1)) {


+

out <- cbind(out, x[i])

out <- cbind(out, ",")

+ }
> out <- cbind(out, x[length(x)])
> write(out, file="C:/data14.txt",
+

ncolumns = 2*length(x))

writeLines(paste( ), sep=,)
Yn

> out <- file("C:/data15.txt", "w") #


> for (i in 1:10) {

data15.txt

1, 2, 3, 4, 5

if (i < 5)

writeLines(paste(i), out, sep=", ")

else if (i == 5) writeLines(paste(i), out, sep="\n")

else if (i < 10) writeLines(paste(i), out, sep=", ")

else

,
*

6, 7, 8, 9, 10

writeLines(paste(i), out, sep="")

+ }
> close(out)

10.3 EXCEL

R EXCEL
(1) .csv.txt

(2) [] [] [
%
'
(3) & (
(.prn, .txt, .csv)]

10

112

10.4 LATEX html


LaTeX xtable xtable()

> library(xtable)
> mytable <- xtable( matrix(1:24,4,6) )
> print(mytable)
% latex table generated in R 2.1.0 by xtable 1.2-4 package
% Sat May 28 14:47:23 2005
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrrrr}
\hline
& 1 & 2 & 3 & 4 & 5 & 6 \\
\hline
1 & 1.00 & 5.00 & 9.00 & 13.00 & 17.00 & 21.00 \\
2 & 2.00 & 6.00 & 10.00 & 14.00 & 18.00 & 22.00 \\
3 & 3.00 & 7.00 & 11.00 & 15.00 & 19.00 & 23.00 \\
4 & 4.00 & 8.00 & 12.00 & 16.00 & 20.00 & 24.00 \\
\hline
\end{tabular}
\end{center}
\end{table}
html *2

> print(mytable, type="html")


<!-- html table generated in R 2.1.0 by xtable 1.2-4 package -->
<!-- Sat May 28 14:48:09 2005 -->
<TABLE border=1>
<TR><TH></TH><TH> 1 </TH><TH> 2 </TH><TH> 3 </TH><TH> 4 </TH><TH> 5 </TH><TH> 6 </TH>
</TR><TR><TD align="right"> 1 </TD><TD align="right"> 1.00 </TD><TD align="right"> 5.00 </TD>
<TD align="right"> 9.00 </TD><TD align="right"> 13.00 </TD><TD align="right"> 17.00 </TD>
<TD align="right"> 21.00 </TD></TR>
<TR><TD align="right"> 2 </TD><TD align="right"> 2.00 </TD><TD align="right"> 6.00 </TD>
<TD align="right"> 10.00 </TD><TD align="right"> 14.00 </TD><TD align="right"> 18.00 </TD>
<TD align="right"> 22.00 </TD></TR>
<TR><TD align="right"> 3 </TD><TD align="right"> 3.00 </TD><TD align="right"> 7.00 </TD>
<TD align="right"> 11.00 </TD><TD align="right"> 15.00 </TD><TD align="right"> 19.00 </TD>
<TD align="right"> 23.00 </TD></TR>
<TR><TD align="right"> 4 </TD><TD align="right"> 4.00 </TD><TD align="right"> 8.00 </TD>
<TD align="right"> 12.00 </TD><TD align="right"> 16.00 </TD><TD align="right"> 20.00 </TD>
<TD align="right"> 24.00 </TD></TR></TABLE>

*2

Hmisc latex()

11

114

11

plot()

11.1
R
R 2

()*1

11.1

11.2
X
3

*1

high (low) level plotting function graphics function 2



RjpWiki

11

115

()

11.3
R
R R UNIX , Linux X11()
Windows windows()
R
R

R help(Devices)

bitmap()

bmp()

dev2bitmap()

jpeg()

JPEG

pdf()

ADOBE PDF

pictex()

LATEX

png()

PNG

postscript()

POSTSCRIPT

quartz()

(Mac OS )

windows()

(Windows )

win.graph()

(Windows )

win.metafile()

Windows

win.print()

(Windows )

x11()

(UNIX )

X11()

(UNIX )

xfig()

Xfig

dev.off() postscript()
dev.off()

# PS file

> data(cars)

> postscript("myplot.eps", horizontal=FALSE, height=9, # horizontal = FALSE


width=14,

pointsize=15)

# TeX ,

> plot(cars, main = "Speed and Stopping Distances of Cars")


> dev.off()

null device
1
() ( myplot.eps )
22

11

116

11.4

()

bmp(), jpeg(),

pdf()

()

dev.list()

dev.next()

dev.prev()

dev.set(which=k)

dev.off(k)

dev.copy(device, which=k)

k device postscript

dev.copy2eps(file=)

eps dev.copy()

dev.print(device,which=k)

k
( postscript)

graphics.off()

PDF png() bmp() jpeg()

> plot(1:10)
> dev.copy(pdf, file="finename.pdf")
> dev.off()

>

# ...

> pdf()

# pdf ()

> plot(1:10)

# -> Rplots.pdf

> dev.off()

eps

# X11 ( OS )

> X11()
> plot(1:10)

> dev.copy2eps(file="finename.eps", width=6) #


>

# ... dev.print() ...

> X11()

# X11 ( OS )

> plot(1:10)

# X11

> dev.print(file="finename.eps",

# EPS

width=10, height=10, horizontal=FALSE)

11

117

Windows R
metafile bmp metafile (.emf)
postscript (.ps , .eps)

11.2 Windows R

11.5 plot()
R plot() plot()
x y

> x <- 1:10


> y <- 1:10

# plot(x , y , )

> plot(x, y)

# (xlim=c(1,10) )

> plot(x, y, xlim=c(10,1)) # x

10
8
6
y
4
2

10

xlim, ylim

10

10

> plot(sin, -pi, 2*pi)

# plot(, , )

> gauss.density <- function(x) 1/sqrt(2*pi)*exp(-x^2/2)

0.3
0.1

0.2

gauss.density (x)

0.0
0.5

0.0

1.0

sin (x)

0.5

1.0

0.4

> plot(gauss.density,-3,3)

2
x

0
x

11

118

3 persp()

> persp(x , y , z , col = ,


theta = , phi = , expand = , border=NA)

> x <- seq(-3,3,length=50)

# x

> y <- x

# y

> rho <- 0.9

# 2

> gauss3d <- function(x,y) {

# 2

1/(2*pi*sqrt(1-rho^2))*exp(-(x^2-2*rho*x*y+y^2) / (2*(1-rho^2)))

+ }
> z <- outer(x,y,gauss3d)

# z

> z[is.na(z)] <- 1

# 1

> persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")

11.6 plot()
plot() type type 9

type=p

()

type=l

()

type=b

type=c

type=o

type=h

type=s

type=S

type=n

()

11

119

> x <- rnorm(10)


> plot(x, type="l")

11.7

log=x

x ( x ) y ( y ) xy ()
()

xlim=c(0, 1)ylim=c(1, 1)

2 x y xlog,

ylog (c(2, 2))

axes=FALSE

TRUE xaxs, yaxs

> x <- rnorm(10)


> plot(x, ylim=c(-30, 30), type = "l")

11.8

main=Title

sub=SubTitle

xlab=X-Labelylab=Y-

x y x

Label

ann = F

( xlab = ylab =
)

tmag=1.2

> x <- rnorm(10)


> plot(x, main="Simple Time Series")

11

120

11.9
par() add=T

() plot() add=T
> plot(sin, -pi, pi, xlab="", ylab="", lty=2)

# sin(x)

> par(new=T)

> plot(cos, -pi, pi, xlab="x", ylab="y")

# cos(x)

> plot(sin, -pi, pi, xlab="x", ylab="y", lty=2) # sin(x)


# cos(x)

> plot(cos, -pi, pi, add=T)

11.10

> x <- runif(100)


> y <- runif(100)

y
0.0

1.0

0.2

0.5

0.4

0.0

0.6

0.5

0.8

1.0

1.0

> plot(x, y, col = ifelse(y>0.5, "red", "blue")) # y > 0.5 ,

0.0

11.3

0.2

0.4

0.6

0.8

1.0

11.4

11.11
frame() plot.new() new

TRUE
> frame()
> plot.new()

12

121

12

12.1
12.1.1 plot()
plot() plot()
plot(x) x x x

x
x 2 2

x 2 names()
x y

> plot(rnorm(10))
> x <- list(1:5, 3:7);

names(x) <- c("X", "Y")

> plot(x)
plot(x, y) x y x y
> x <- rnorm(10);

y <- rnorm(10)

> plot(x,y)
plot(y x)
> x <- rnorm(10);

y <- rnorm(10)

> plot(y ~ x)
plot(f) f f
> f <- factor(c(rep("A",3), rep("B",5)))
> plot(f)
plot(f, y) f y f y
> x <- factor(c(rep("A",3), rep("B",5)));
> plot(f, y)

y <- rnorm(8)

12

122

plot(df) df
plot( expr) expr + ( a+b+c )

> plot(~ group, data=sleep)


> plot(~ extra, data=sleep)
plot(y expr) y expr + a+b+c
expr y

12.1.2 dotchart()
)

*
)

dotchart() *1

dotchart(, groups=,

gdata=NULL, labels=, ...)

12.1.3 stripchart()
)

stripchart()

stripchart( ~ ,
vertical = F, group.names=,...)

12.1.4 sunflowerplot()

> dotchart(1:10, group=c(rep(1:2,5)),

+
+
,

labels=paste("sample", 1:10))

*
,

*
)

> stripchart(y ~ x)
+
,

> y <- rnorm(20); x <- factor(rep(1:2,10))

sunflowerplot() 1

)
*

> x <- round(rnorm(50), d=1)

sunflowerplot(x , y , digits=6,

> y <- data.frame(x, x)

xlab = "", xlim = NULL, add = F, ...)


+

> sunflowerplot(y)
,
+

12.1.5 curve()

curve() n

curve(, from=, to=, n = ,

add = FALSE, type = "l", xlim = NULL, ...)

12.1.6 matplot()

*
)

+
,

> curve(sin(x^2)*exp(-x^2),-pi,pi)

matplot()
matpoints() matlines()
*1

rug()

plot(density(faithful$eruptions))
rug(faithful$eruptions, side=1)

12

123

*
)

> myfunc <- function(x,y) sin(x/20 * pi * y)

matplot( 2 ,

> sines

type = "p", lty = 1:5, lwd = 1,

<- outer(1:20, 1:4, myfunc)

> matplot(sines, pch = 1:4, type = "o")


+
,

pch = NULL, col = 1:6, ...)

12.1.7

sample 9
1

sample 7

round.x..d...1..1

sample 1

sample 10

sample 3

sample 5

sample 8
2

sample 6
sample 4
1

sample 2

10

1.0

0.5

0.0

0.5

1.0

1.5

2.0

round.x..d...1.

12.1 dotchart()

12.2 stripchart()

12.3 sunflowerplot()

1.0

0.4

0.30

0.5

0.25

Density

0.2

0.0

sines

0.3

0.20
0.15

0.0

1.0

0.00

0.05

0.1

0.5

0.10

sin(x^2) * exp(x^2)

0.5

density(x = faithful$eruptions)

10

15

20

N = 272 Bandwidth = 0.3348

12.4 curve()

12.5 matplot()

12.6 rug()

12.2
12.2.1 hist()
hist()
() *2

> x <- rnorm(50)

> hist(x, breaks = seq(-3,3,1) )

# -3 -3 1

> hist(x, breaks = c(-3,-1,0,0.5,3) )

# ()

*2

12

124

12.2.2 barplot()
barplot()

*
)

barplot(, ...)
+

> barplot(matrix(1:20, 5), col=rainbow(5))


+
,

barplot(, ...)

> barplot(1:10)

barplot() barplot() x
lines

angle=45

beside=F

T F

col=rainbow(10)

density=30

horiz=F

legend = rownames(x)

names=

space=1

width=

12.2.3 pie()
)

*
)

pie()

pie(, labels = names(x), radius = 0.8,

> pie(1:10, r=1,

+
,

density = NULL, angle = 45, col = NULL, ...)

pie()

col=rainbow(10))

*
,

angle=45

border=NULL

NA

col=rainbow(10)

density=30

main=Title

radius=0.8

11

12.2.4 boxplot()
)

*
)

boxplot()

boxplot(x, range = 1.5, width = NULL,


horizontal = FALSE, add = FALSE,...)

boxplot(x ~ )
+

> x <- rnorm(100)

> boxplot(x)
> boxplot(len ~ dose, data = ToothGrowth)
,
+
,

12

125

boxplot()

boxwex = 0.8

horizontal=F

notch=F

notch

outwex = 0.5

outlier

range=1.5

range

range 1.5
Q3 + 1.5(Q3Q1) range
0

staplewex = 0.5

width=

12.2.5

40

10

20

5
0
3

12.7 hist()

12.9 barplot()2

35

12.8 barplot()1

30

25

3
7

-1

15

20

-2

10

10

-3

Frequency

60

15

80

10

Histogram of x

0.5

12.10 pie()

12.11 boxplot()1

12.12 boxplot()2

12

126

12.3
12.3.1 fourfoldplot()
)

)
*

> fourfoldplot(x, col=1:2)


,
+

fourfoldplot() 1 2 2 2

> x <- matrix(1:4,2)

fourfoldplot(2*2 )

12.3.2 mosaicplot()
)

*
)

mosaicplot(, data=)
+

> mosaicplot(~ Sex+Age+Survived, data = Titanic)


+
,

mosaicplot() dir=h (=v)

> mosaicplot(Titanic, color = T)

mosaicplot()

12.3.3 assocplot()
)

)
*

> assocplot(x)
,
+

assocplot() Cohen-Friendly Association Plots

> x <- margin.table(HairEyeColor, c(1,2))

assocplot()

12.3.4
Row: A

Titanic

2nd
Child Adult

Child

3rd
Adult

Child

Crew
Adult

Eye

Hazel
Green
Class

Row: B

12.13 fourfoldplot()

Blue

Sex
No
Female
Yes

Col: B

Col: A

Male
Yes

Brown

No

1st
Child Adult

Black

Brown

Red
Hair

12.14 mosaicplot()

12.15 assocplot()

Blond

12

127

12.4
12.4.1 stars()
stars()

> stars(mtcars[, 1:6], locations = c(0,0), radius = T,


+

key.loc=c(0,0.0), main="Motor Trend Cars")

> stars(mtcars[, 1:7], len = 0.8, key.loc = c(12, 1.5),


+

main = "Motor Trend Cars", draw.segments = TRUE)

12.4.2 symbols()
symbols()

> x <- 1:10;

y <- sort(10*runif(10));

z <- runif(10)

> symbols(x, y, thermometers=cbind(0.5,1,z), inches=0.5, fg=1:10)

circles=

squares=

rectangles=

stars=3 0 1

thermometers=c() thermometers=c(
1 2)

boxplots=c( 1 2)

fg=

bg=

inches=F x inches=T
1 inches=

12.4.3 pairs()
pairs() pairs()

> pairs(iris[1:4])

>
> pairs(~ Fertility + Education + Catholic, data = swiss,
+

subset = Education < 20, main = "Education < 20")

12

128

12.4.4 coplot()
coplot() x y z ( z )
z y x

coplot(y x | z) z z y x z
z y x

coplot(y x | z1 z2 ) 2 z1 z2 x y
> x <- 1:10;

y <- rnorm(10);

z <- x*y

> coplot(y ~ x | z)

12.4.5
Motor Trend Cars

Motor Trend Cars


cyl

Mazda RX4 Wag

Datsun 710

Hornet 4 Drive
Valiant
Hornet Sportabout

Mazda RX4

10

disp

Merc 240D

Merc 280

Merc 230

Merc 450SE

Merc 280C

Merc 450SL

Merc 450SLC
Lincoln Continental
Fiat 128
Cadillac Fleetwood
Chrysler Imperial

Honda Civic

Toyota Corolla
Dodge Challenger
Camaro Z28
Toyota Corona
AMC Javelin

mpg

hp

Duster 360

Fiat X19

Porsche 9142

Lotus Europa

Ford Pantera L
cyl

disp
drat

wt
Maserati Bora

Volvo 142E

2.0

3.0

4.0

mpg

1.5

10

Given : z
4

15

6.5

90

7.5

80

5.5

60

4.0

70

4.5

Fertility
2

10

10

0.0

0.4

10

Education

2.0

15

0.4

Sepal.Width

3.0

10

12.18 symbols()

Education < 20

2.5

wt

Sepal.Length

6
x

qsec

12.17 stars()2

0.5

hp
drat

12.16 stars()1

Ferrari Dino

Pontiac Firebird

y
0.4

100
80

0.8

0.4

60
0

0.5

20

40

Catholic

Petal.Width

0.0

3
2
1
2.5
1.5

0.8

Petal.Length

2
4.5

5.5

6.5

7.5

60

70

80

90

20

40

60

80

10

100

12.19 pairs()1

12.20 pairs()2

12.21 coplot()

12

129

12.5 3
12.5.1 image()
image() 3

> x <- 10*(1:nrow(volcano));

y <- 10*(1:ncol(volcano))

> image(x, y, volcano, col = terrain.colors(100), axes = FALSE)

12.5.2 persp()
persp() 3

> x <- seq(-10, 10, length= 50);

y <- x

> f <- function(x, y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }


> z <- outer(x, y, f);
> persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = rainbow(50), border=NA)

12.5.3 contour()
contour() 3 filled.contour()

> x

<- -6:16

> contour(outer(x, x), method = "edge", vfont = c("sans serif", "plain"))

12.5.4 scatterplot3d()
scatterplot3d 3 scatterplot3d()
scatterplot3d

> library(scatterplot3d)
> z <- seq(-10, 10, 0.01);

x <- cos(z);

y <- sin(z)

> scatterplot3d(x, y, z, highlight.3d=TRUE, col.axis="blue",


+

col.grid="lightblue", main="Plot-1", pch=20)

>
> temp <- seq(-pi, 0, length = 50)
> x <- c(rep(1, 50) %*% t(cos(temp)))
> y <- c(cos(temp) %*% t(sin(temp)))
> z <- c(sin(temp) %*% t(sin(temp)))
> scatterplot3d(x, y, z, highlight.3d=TRUE, col.axis="blue",
+

col.grid="lightblue", main="Plot-2", pch=20)

12.5.5 lattice
lattice S Trellis R
cloud() wireframe()

12

130

> library(lattice)
> data(volcano)
> wireframe(volcano, shade = TRUE, aspect = c(61/87, 0.4),
+

light.source = c(10,0,10))
lattice

barchart()

bwplot()

densityplot()

dotplot()

histogram()

qqmath()

stripplot()

rfs()

qq()

2 q-q

xyplot()

trellis plot()

levelplot()

contourplot()

cloud()

()

wireframe()

()

splom()

parallel()

12.5.6

0.4

0.6

0.8

1.0

Math can be beautiful ...

0.0

0.2

x
cos(r2)er

0.0

0.2

0.4

0.6

0.8

1.0

12.23 persp()

Plot1

Plot2

12.24 contour()

0.8

10

1.0

12.22 image()

1.0
0.5

0.2

0.5
0.0

0.0

1.0
0.5

0.0

0.5

1.0

12.25 scatterplot3d()1

column

row

0.5
0.0

10

0.5

1.0

z
0.4

0.6

volcano

1.0

1.0

1.0
0.5

0.0

0.5

1.0

12.26 scatterplot3d()2

12.27 latticewireframe()

12.5.7 grid
grid R

graphics graphics
lattice
*3
*3

Paul Murrell http : //www.stat.auckland.ac.nz/ paul/


PDF

13

131

13

13.1

points(x, y) , points(c(x, y))

x y (

points() type p )
pch

points(approx(x, y))

lines(x, y) , lines(c(x, y))

x y
( lines()
type l )

abline(a, b), abline(c(a, b))

a b y = a + bx

abline(h = y)

abline(v = x)

abline(result)

result lm()

grid(a, b)

a b col, lty, lwd

segments(x0, y0, x1, y1)

arrows(x0, y0, x1, y1)

(x0y0) (x1 y1)

rect(x0, y0, x1, y1)

(x0y0) (x1 y1)

(x0y0) (x1 y1)

col, border, density

text(x, y, labels)

(xy)
text srt = ()
x 45

mtext(text, side = 3, line = 0,

text side

at = NA)

(1234)

line at

13

132

box()

box(lty=1373, col = red)


(
)

title(main, sub)

main sub

tmag

axis(side=4, labels=F)

(1234) labels FALSE


at=1:10

axis(side=1, pos=0)

pos (side=3)

(side=1) y (side=4) (side=2)


x pos pos = 0

legend(x, y, legend)

(xy) legend
ncol 2

legend(locator(1), legend=)

locator()

legend(..., fill=v , col=v)

legend(..., lty=v , lwd=v ,

()

pch=v)
polygon(x,y)

(xy) x y
NA

polygon(x, y, density=c(10, 20),

density /

angle=c(45, 45))

angle
()

border col , lty xpd

13.2
( 1) axis() box() legend()
polygon()

> plot(rnorm(50), rnorm(50), xlim=c(-3,6), ylim=c(-3,3), axes = F, ann=F)


> axis(1, pos = 0, at = -3:6, adj = 0, col = 2)

# X

> axis(2, pos = 0, at = -3:6, adj = 1, las = 2)

# Y

> box()
> legend(2, 3, paste("sin(",6:9,"x)"), col=6:9,
+

pch=3, ncol=2, cex=1.1, pt.bg="pink")

# (5,9)

> polygon(3:6, c(-2,-1,-2,-1), density=c(10, 20), angle=c(-45, 45))


> arrows(5, -1, 4, 2, col="blue")

# (5,-1) (4,2)

13

133

( 2) polygon() *1
4 x 4 2 x 4

polygon() xvals rep(0,10)


x rev(xvals) rev(dvals)

> plot(dnorm, -4, 4)


> xvals <- seq(2, 4, length=10)

# x 10 ()

> dvals <- dnorm(xvals)

> polygon(c(xvals,rev(xvals)),
+ c(rep(0,10),rev(dvals)),col="gray") #
> title("Title")

> mtext("sub-title", side=4)

(1) (2)

sin( 6 x)
sin( 7 x)

0.4

Title

sin( 8 x)
sin( 9 x)

0.3

subtitle

0.2

0
3

dnorm (x)

0.1

0.0

13.1

(1)

13.2

(2)

13.3
text() mtext() axis() title()
expression()

> text(x,y,expression(paste(bggroup("(",atop(n,x),")"),p^x, q^{n-x})))

> ?plotmath
> demo(plotmath)
> example(plotmath)

*1

RjpWiki

13

134

13

135

13

136

13

137

13

138

13.4 eps
R eps ADBE

13.4.1 Tgif
Tgif eps pstoedit http : //www.pstoedit.net/pstoedit eps obj
Windows Tgif

13

139

13.4.2 OpenOffice.org draw

(1) Ghost Script (7.04 ?) GSView http : //f orum.nif ty.com/f dtp/install/win/gs800.htm

(2) OpenOffice.org http : //ja.openof f ice.org/marketing/news/110.html


OpenOffice.org http : //oooug.jp/start/
OpenOffice.org1.1 (04/03/08 )

(3) pstoedit http : //www.pstoedit.net/pstoedit GSview pstoedit


( GS 8.00 C:/Program Files/Ghostgum/pstoedit )
Windows XP

(1) GSview [Edit] [Convert to vector format...] () WMF EMF (


OK ) ( R win.metafile() emf )

(2) OpenOffice.org draw [] []

(3) eps export

14

140

14

14.1
par()
2
2
par() *1
col

> par(col="red")

> plot(1:10, col="red")

14.2
par()

par()

par()

par(, )
par(c(, ))
par(col=2)

par(col=2, lty=3)
par(list(col=2, lty=3))

*1

par(cin)
par(cra)par(csi)par(cxy)par(din)

par(cin)/par(pin)

14

141

14.2.1 par()
par() *2
> par(new=T)

# new TRUE

> par(ask=TRUE)

> help(par)

14.2.2
par()
R 1

> oldpar <- par(no.readonly = TRUE)

> oldpar <- par(col=1, lty=2)

> par(oldpar)

par()

> myfunc <- function () {


+

oldpar <- par(no.readonly = TRUE)

on.exit(par(oldpar))

par(col=2);

plot(1:10)

+ }

14.2.3
par() plot()

14.1

*2

14.2

new TRUE ask TRUE help


example

14

142

*3

14.2.4
xpd = F FALSE TRUE
NA

> library(rpart)
> result <- rpart(Species ~ ., data=iris)

# par(xpd=F) par(xpd=NA)

> plot(result)
> text(result)
Petal.Length<
2.45
|
Petal.Length< 2.45
|

tosa

Petal.Width< 1.75
setosa

versicolor

Petal.Width< 1.75

virginic
versicolor

14.3 par(xpd=F)

virginica

14.4 par(xpd=NA)

14.2.5 plot region

pin = c(6,6)

plt = c(0.1, 0.9, 0.1, 0.9)

x y c(0, 1, 0, 1)

ps = 12

pty = m

s m m

*3

ps, eps

14

143

par(usr)

> par("usr")

14.2.6 figure region

fig = c(0, 1, 0, 1)

x y c(0, 1, 0, 1)
c(0, 0.5, 0.5, 1)

par(new=T)
S

fin = c(5,5)

par(fin) [6.968749

6.958332] c(5, 5)

par(new=T) S

14.2.7

mai = c(0.85, 0.68, 0.68, 0.35)

mar
pltpin

mex = 1

0.5

mar = c(5, 4, 4, 2)

mex
3
4 ( 4 mex ) mai
pltpin

omi = c(0, 0, 0.8, 0)

(outer margins

in inches)
oma = c(2, 0, 3, 0)

outer marginmex

omd = c(0, 1, 0, 1)

0 1

(x1 , x2 , y1 , y2 )
y mar

> par(mar=c(5,4,5,4))
> plot(1:10)
> axis(side=4)

14

144

14.3
par() plot()

pch 2 par()

()

> plot(1:10, pch="+")

# "+"

> par(pch="+")

# "+"

> plot(1:10)

# "+"

> plot(1:20)

# "+"

14.3.1
col col.axis, col.lab, col.main, col.sub

col = 1, col = blue

(color) col = ( 1 )

1
col = rgb(1, 0, 0) col = rgb() 16
col = #FFFFFF
col = rainbow(10)

rainbow(n) heat.colors(n) terrain.colors(n) topo.colors(n)

cm.colors(n) col
col = hsv(.5, .5, .5),

hsv

col = gray(0.8)
gamma = 1.0

14.3.2
pch = pch = 0 25
+

pch

pch

pch

pch

pch

pch

pch

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

14.3.3

14

145

adj = 0

( 00.51) adj =

c(x,y) x y
cex = 1

1 csi
cex.axis, cex.lab,

cex.main, cex.sub
ps = 20

text(x, y, labels=

(x, y) labels ()

, srt=90)

( x ) crt ()

col = 1

col.axis, col.lab, col.main, col.sub

font = 1

( 1234
5 (Adobe symbol encoding) ) font.axis, font.lab,

font.main, font.sub

family=


serifsansmonosymbol

14.3.4
*4

lwd = 1

(line width)

lty=0 lty=blank

(line type)

lty=1 lty=solid

(line type)

lty=2 lty=dashed

(line type)

lty=3 lty=dotted

(line type)

lty=4 lty=dotdash

(line type)

lty=5 lty=longdash

(line type)

lty=6 lty=twodash

(line type)

type = p

()

type = l

()

type = b

type = c

type = o

type = h

type = s

type = S

type = n

*4

lend0round1butt2squarelheightljoin0round1mitre
2bevellmitre

14

146

14.3.5

bg = blue

fg = blue

bty = o

bty = l

bty = 7

bty = c

bty = u

bty =

bty = n

()

14.3.6

ann = F

FALSE

las = 0

las = 1

las = 2

las = 3

lab = c(5,5,7)

3 x y
( R 2.1.1 )

mgp = c(3,1,0)

3
(mex )

tck = NA

tck = 1

tcl = 0.5

xaxt = s yaxt = s

NA tcl = 0.5

(mex)
tcl = NA tck

0.01

t
xaxt = n yaxt = n

xaxt = n yaxt = n
axes = F

xaxs = r yaxs = r

x y 4 %

xaxs = i yaxs = i

x y

par(xaxp) par(yaxp)

xy

xlog = F ylog = F

x y TRUE
FALSE

15

147

15

R
R

15.1 locator()
locator() locator()

Windows R

> locator()

> locator(10)

# 10 ( 512 )

locator() x y

# z x y

> z <- locator()

> text(locator(1), "Outlier", adj=0)

15.2 identify()
identify()
locator()

> x <- rnorm(20);

y <- rnorm(20)

# y 20

> plot(x, y)

# (x, y)

> identify(x, y, x)

# x

> identify(x, y, y)

# y

> identify(x, y)

[1]

8 11 16 20

identify() 3

148

15

16

11

20

identify() x y 8 11 16
20
> pt <- identify(x,y,y) # identify(x,y) identify(x,y,x)
# pt

> pt
[1]

8 11 16 20

( 1) plot=F ()

( 2) 0.25

warning: no point with 0.25 inches


warning: nearest point already identified

15.3

15.3.1

15

149

par()

oma 4 mex mex 1 4

> par(oma = c(0, 0, 4, 0))

mfcol = c(m,n), mfrow = c(m,n)

m n mfcol mfrow
1 mfrow=c(1,1)
mfcol=c(1,1)

mfg = c(i,j,m,n)

m n
i j

fig = c(4,9,1,4)/10

22

> par(mfrow=c(2,2))
1

> plot(sin)
> plot(cos)
> plot(asin)
> plot(acos)
outer = T mtext

> mtext(side = 3, line=1, outer=T, text = "Title", cex=2)


(oma)

0.4

0.6

0.8

1.0

0.0

0.2

0.4

0.6

0.8

1.0

0.6

0.8

1.0

0.9
0.2

0.4

0.6

0.8

1.0

0.0

0.4

0.6

0.8

1.0

0.6

0.8

1.0

0.2

0.4

0.6

0.8

1.0

0.0

0.2

0.4

15.1

1.0

acos (x)

0.5
0.0

0.5
0.0

0.0
0.0

1.0

asin (x)

1.5
1.0

acos (x)

0.5

1.5
1.0
0.5
0.0

asin (x)

0.2

1.5

1.5

0.2

0.8

cos (x)

0.6
0.0

0.0

0.7

0.6
0.4

sin (x)

0.2
0.0

cos (x)

0.6 0.7 0.8 0.9 1.0

0.4
0.0

0.2

sin (x)

0.6

0.8

0.8

1.0

Title

0.0

0.2

0.4

0.6

0.8

1.0

0.0

0.2

0.4

15.2

( 1) frame() 1

( 2) stars pairs

15

150

15.3.2
mfrow mfcol

layout()
layout() mat

> mat <- matrix(c(1,0,2,2), 2, 2, byrow = TRUE)


> mat
[,1] [,2]

# ()

[1,]

# ( 1 )

[2,]

# ( --------- 2 --------- )

> layout(mat)

()

> plot(sin)

0.4
0.0

0.2

sin (x)

0.6

0.8

> plot(cos)

0.0

0.2

0.4

0.6

0.8

1.0

0.8
0.7
0.6

cos (x)

0.9

1.0

0.0

0.2

0.4

0.6

0.8

1.0

layout.show(n) lcm(x)
> layout(matrix(c(1,3,2,2), 2, 2, byrow = TRUE), respect=T, widths=lcm(5), heights=lcm(5))
> plot(sin)
> plot(cos)
> plot(acos)
split.screen()
split.screen() 2 c( m, n ) *1
2

> split.screen(c(2,1))
[1] 1 2
1 2 screen
2 3

*1

15

151

> split.screen(c(1,3), screen = 2)


[1] 3 4 5
> screen(1); plot(rnorm(10))

# 1

> screen(3); plot(rnorm(10), type="l")

# 3

> screen(4); plot(rnorm(10), type="S")

# 4

> screen(5); plot(rnorm(10), type="h")

# 5

()

frame() erase.screen()
1

close.screen(all=T)

15.3.3
add=T 2 x y

> plot(cos, -pi, pi, lty=2)


> curve(sin, add=T)
add=T new

( 1) par(new=T) 2 plot()
1 axes=F , xlab=ylab=
ann=T

( 2) par(new=T)
xlim = c(x0, x1)ylim = c(y0,

y1)

15

152

x <- rnorm(100)

# 100

hist(x, xlim=c(-4,4), ylim=c(0,0.5), prob=T, ann=F)

par(new=T)

plot(density(x), xlim=c(-4,4), ylim=c(0,0.5),


#

xlab="", ylab="", main="", col="red")

axis() 2 plot(density(x)...) y

> axis(side=4)

0.5
0.4
0.3

0.4
0.3
4

0
x

15.3 axis()

0.2
0.1
0.0

0.0

0.1

0.2

Density
0.0

0.1

0.2

Density

0.3

0.4

0.5

Histogram of x

0.5

Histogram of x

15.4 axis()

() axis() y mar

VI

16

154

16

16.1
10
2 xy *1

> x <- c(0.7,-1.6,-0.2,-1.2,-0.1,3.4,3.7,0.8,0.0,2.0) # 1


> y <- c(1.9, 0.8, 1.1, 0.1,-0.1,4.4,5.5,1.6,4.6,3.4) # 2
*2

ave(x)

fivenum(x)

IQR(x)

max(x)

mean(x)

median(x)

min(x)

()

quantile(x)

range(x)

sd(x)

sum(x)

var(x,y)

weighted.mean(x)

summary()

# x

> quantile(x)
0%

25%

50%

75%

100%

-1.600 -0.175

0.350

1.700

3.700
# y

> summary(y)
Min. 1st Qu.
-0.100

Median

0.875

1.750

Mean 3rd Qu.


2.330

4.150

Max.
5.500

16.1.1
pie(result) barplot(result)

> breaks <- seq(-2, 4, 2)

> ( result <- table(cut(x, breaks)) )

# result

(-2,0]

(0,2]

(2,4]

*1
*2

170
5 fivenum() 4 IQR() 3 1
quantile() 1 3 range()
sum((x-mean(x))2)mean((x-mean(x))3)/(sd(x)3)mean((x-mean(x))4)/(sd(x)4)
0 3 e1071
skewness()kurtosis()

16

155

16.1.2
var()
x n E() var(x)

var(x) =

%
n $
E(x2 ) {E(x)}2
n1

var() (n 1)/n

> var(x)
[1] 3.200556
> variance <- function(x) var(x)*(length(x)-1)/length(x)

> variance(x)
[1] 2.8805
#

> sd(x)
[1] 1.789010

> sqrt(variance(x))
[1] 1.697204

16.1.3
2 var() 1
2 var()

var() (n 1)/n

cor() 1 2

> var(x, y)
[1] 2.848333
> cor(x, y)
[1] 0.7951702

> my.cor <- function(x) {


+

tmpcor <- cor(x)

if (det(tmpcor) != 0)

sol <- solve(tmpcor)

else { library(MASS);

sol <- ginv(tmpcor) }

d <- diag(sol)

sol <- -sol/sqrt(outer(d,d))

rownames(sol) <- paste("Var", 1:ncol(x))

colnames(sol) <- paste("Var", 1:ncol(x))

return(sol)

+ }
> sampledata <- matrix(c(1:9), ncol=3, byrow=T)
> my.cor(sampledata)

16

156

Var 1 Var 2 Var 3


Var 1

-1

-1

-1

Var 2

-1

-1

-1

Var 3

-1

-1

-1

16.1.4
x 0 1
scale(x) x
0 ()

1 () 2 *3

> scale(x)
[,1]
[1,] -0.02794842
[2,] -1.31357592
................
[10,]

0.69871059

attr(,"scaled:center")
[1] 0.75
attr(,"scaled:scale")
[1] 1.789010

16.2
R f (x) P (X x) min{x : P (X x) > q}

16.2.1

xxx qxxx t pt
qt

(xxx )

(pdf)

dxxx(q)

q norm
dnorm(q)

(cdf)

pxxx(q)

q norm
pnorm(q)

(quantile)

qxxx(p)

p norm qnorm(p)

rxxx(n)

n norm
rnorm(n)

*3

scale() center=F scale=F

16

157

16.3 R
R qtukey () ptukey (
) dmultinom rmultinom
pbirthday qbirthday*4

beta

binom
birthday

cauchy

chisq
exp

shape1, shape2, ncp


classes, coincident, prob
size, prob
location, scale
df, ncp
rate

df1, df2, ncp

gamma

shape, scale

geom

prob

hyper

n, m, k

lnorm

meanlog, sdlog

logis

location, scale

multinom

n, size, prob

nbinom

size, prob

norm

mean, sd

pois

lambda

signrank

m, n

t
unif

df, ncp
min, max

tukey

nmeans, df

weibull

shape, scale

wilcox

m, n

( 1) binom lower.tail TRUE


P[X x] FALSE P[X > x] *5

dbinom(x, size, prob)

# x : , prob :

pbinom(q, size, prob, lower.tail = TRUE)

# q : quantile

qbinom(p, size, prob, lower.tail = TRUE)

# p :

rbinom(n, size, prob)

# n :

size :

( 2) 4 t 0.05 qt(0.025, 4) qt(0.975, 4)

*4

MASS mvrnorm() mvtnorm rmvt()


mvtnorm dmvnorm()pmvnorm()rmvnorm()
*5 log, log.p TRUE

158

0.0

0.1

0.2

0.3

16

-4

-2.78

2.78

16.1 pt(), qt(), dt()

( 3) norm f(x)
# ()

> dnorm(0)
[1] 0.3989423
> rnorm(5)

[1] -2.0024918 -0.5996763 -0.3108348 1.2590405 0.3661534


( 4)
#

> plot(0:10, dbinom(0:10, 10, 0.5), type="h", lwd=5)

0.0

0.15
0.00

0.05

0.10

dbinom(0:10, 10, 0.5)

0.2
0.1

dnorm (x)

0.3

0.20

0.4

0.25

> curve(dnorm, -4, 4, type="l")

16.2

10

0:10

16.3

( 5) (p, n - p - 1) F 100 % qf(1 - alpha, p, n - p - 1)


(2, 3) F 5%

> qf(0.95, 2, 3)
[1] 9.552094

# qf(0.05, 2, 3, lower=F)

16

159

16.3.1 set.seed()
R ( R
) set.seed()

# 5

> runif(5)

[1] 0.8039566 0.6593698 0.8120159 0.1279622 0.1115031


#

> runif(5)

[1] 0.5694816 0.4504077 0.1823374 0.4573758 0.9061499


> set.seed(101); runif(5)

# (seed)

[1] 0.37219838 0.04382482 0.70968402 0.65769040 0.24985572


> set.seed(101); runif(5)

[1] 0.37219838 0.04382482 0.70968402 0.65769040 0.24985572

16.3.2 2
r 2 r2norm()

> r2norm <- function(n, mu, sigma, rho) {


+

tmp <- rnorm(n)

<- mu+sigma*tmp

<- rho*x + sqrt(1-rho^2)*rnorm(n)

return(data.frame(x=x,y=y))

+ }
> mydata <- r2norm(100, 0, 1, 0.5)
> cor(mydata$x,mydata$y)
[1] 0.5756098

16.3.3 3
3
3 r3norm()

> r3norm <- function(mu, A, n) {


+

U <- svd(A)$u;

V <- svd(A)$v;

D <- diag(sqrt(svd(A)$d))

B <- U %*% D %*% t(V)

w <- c()

for (i in 1:n) w <- append(w, list(mu + B%*%cbind(rnorm(3))))

return(w)

# A

+ }
> mu <- cbind(c(1,1,1))
> A <- array(c(2,1,1,1,2,1,1,1,2), dim=c(3,3))
> w <- r3norm(mu, A, 2000)

# ()

16

160

3 t

p N(0,Ip )

V = C%*%t(C)
X = sqrt(m/R)*Z p t met(p,m,0,Ip )
Y = +C%*%X p t met(p,m,,V)
3 t met3()

> met3 <- function(m, mu, V, n) {


: , mu : , V : , n

# m

<- svd(V)$u;

<- U %*% D %% t(V1)

w <- c()

for (i in 1:n) {

V1 <- svd(V)$v;

<- diag(sqrt(svd(V)$d))

R <- 0

for (j in 1:m) R <- R + rnorm(1)^2

w <- append(w, list(mu + B %*% (cbind(rnorm(3))*sqrt(m/R))))

return(w)

+ }
m/(m 2) V m > 2) t

> mu <- cbind(c(1,1,1))


> V

<- array(c(2,1,1,1,2,1,1,1,2), dim=c(3,3))

> n

<- 1000

> w

<- met3(5, mu, V, n)

> sm <- 0
> for (i in 1:n) { sm <- sm + w[[i]] }
> sm <- sm/n
> sv <- 0
> for (i in 1:n) { sv <- sv + (w[[i]]-sm) %*% t(w[[i]]-sm) }
> sv <- sv/n

16.3.4
U
X = F 1 (U )

P (X x) = P (F 1 (U ) x) = P (U F (x)) = F (x)

X F

16

161

( 1) F (x) = 1 exp(x) log(1 x) X = log(1 U ) X


1 1 U U X = log(U ) U

1 ( x > 0)

( 2) () f (x) = 1/2 exp(|x|) U1 , U2


U1 1/2 log(U2 ) U1 1/2 log(U2 )

> rlaplace <- function(n) {


+

u <- log(runif(n))

v <- ifelse(runif(n)>1/2, 1, -1)

return(u*v)

+ }
> x <- rlaplace(1000)

16.3.5

()

f (x)
g(x)
c( 1) f (x) c g(x) ()

h(x) = f (x)/{c g(x)}

(1) u < runif(1)


(2) v < g(x)
(3) u h(v) v
f (x) = 1/2 sin(x)

g(x) = 1/

(0 < x < )

(0 < x < )

c = /2

f (x) c g(x) h(x) = sin(x) myrand (


)

> myrand <- function(x) {


+

y <- c();

while (i <= x) {

u <- runif(1);

if (u < w){

v <- pi*runif(1);

y <- append(y, v);

+
+

i <- 1

}
}

i <- i+1

w <- sin(v)

16

162

return(y)

+ }
> mydata <- myrand(1000)

16.3.6 2 x 2
2 x 2 r2dtable()

n
r
c (cr )
r,c 22 n

> x <- r2dtable(2, c(10,10), c(15,5))


> x
[[1]]
[,1] [,2]
[1,]

[2,]

[[2]]
[,1] [,2]
[1,]

[2,]

16.4
n m sample()
replace=FALSE

> n <- 20;

m <- 5

> x <- 1:n

# n

> sample(x, m, replace=TRUE)

[1]

5 18 20 18

5
# m = n

> sample(x)
[1]

6 11

1 14

7 15 20 16 12

> sample(c(0,1), 100, replace=TRUE)

5 18 17 13 10

8 19

# 100

[1] 1 1 1 1 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0 1 0 0 1 1 1 1 0 1 0 0 1 1 0 1 0 0 0
[38] 0 0 1 0 0 0 0 1 1 0 0 1 1 1 0 1 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 0 1 1 0 0 1
[75] 1 1 0 0 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 0 0 0 0 0 1 1
( 1/n )

> p <- runif(n);

p <- p/sum(p)

> sample(x, m, replace=TRUE, prob=p)


[1] 17

4 16 12 20

17

163

17

17.1
factor() table()
*1

> data(warpbreaks)

# 1

> attach(warpbreaks)

> fc <- factor(tension)

> levels(fc)

[1] "L" "M" "H"


# fc

> table(fc)
fc
L

18 18 18
cut()

> tb <- factor(cut(breaks, breaks = 10+10*(0:6)))


> table(tb, fc)
fc
tb

L M H

(10,20] 3 6 8
(20,30] 7 7 7
.............
(60,70] 2 0 0
tapply() tapply()

> # tapply()
> ( mymeans <- tapply(breaks, fc, mean) )
L

# breaks

36.38889 26.38889 21.66667


> ( mysd <- tapply(breaks, fc, sd) )
L

16.446487

9.121009

8.352527

*1

xtabs()

17

164

summary() fivenum() stem() stem()


stem(, x) (=1) x

> stem(breaks)
The decimal point is 1 digit(s) to the right of the |
1 | 0234555667788899
2 | 001111445666678889999
3 | 00156699
4 | 1234
5 | 124
6 | 7
7 | 0
> summary(breaks)
Min. 1st Qu.
10.00

Median

18.25

26.00

> fivenum(breaks)

Mean 3rd Qu.


28.15

34.00

Max.
70.00

[1] 10 18 26 35 70
1 2

17.2
1 1 2 1
f (x) = 0.6(x) + 0.4(x)
generator()

> truedensity <- function (x) {


+

0.6/sqrt(2*pi)*exp(-(x+1)^2/2) + 0.4/sqrt(2*pi)*exp(-(x-2)^2/2)

+ }
> curve(truedensity, xlim=c(-6,6), ylim=c(0,0.3), col=2)
f (x)

> generator <- function(n) {


+

data1 <- rnorm(n)-1

# (x)

data2 <- rnorm(n)+2

# (x)

data3 <- (runif(n) <= 0.6)

# 0.6 data1

data1*data3+data2*(1-data3) # 0.4 data2

+ }
hist() R probability=T

> x <- generator(1000)


> hist(x)

17

165

100

Frequency

0.15

0.00

0.05

50

0.10

truedensity (x)

0.20

150

0.25

200

0.30

Histogram of x

17.1

17.2

17.3
hist()
log2 n + 1 ( n )
Sturges (1926!!) (
)
MASS truehist() ( Scott (1992) )
KernSmooth dpih() ( Wand (1995) )

> library(MASS)
> x <- generator(1000)

# hist(x, breaks="Scott")

> truehist(x)

# hist() breaks Sturges FD


#

> library(KernSmooth)
KernSmooth 2.22 installed
Copyright M. P. Wand 1997
> x <- generator(1000)
> h <- dpih(x)

# bin x

> bins <- seq(min(x)-0.1, max(x)+0.1+h, by=h)

# bin

> hist(x, breaks=bins)

60
0

0.00

20

0.05

40

0.10

Frequency

0.15

80

0.20

100

Histogram of x

2
x

2
x

17

166

( 50 )

> library(KernSmooth)
> x <- generator(100)
> h <- dpih(x)
> bins <- seq(min(x)-2*h, max(x)+h, by=h)
#

> hist(x, breaks=bins)


> bins <- seq(min(x)-3*h/2, max(x)+3*h/2, by=h)

> hist(x, breaks=bins)

20
15

Frequency

10

15
10
0

Frequency

20

25

Histogram of x

25

Histogram of x

17.4
density()

> data <- generator(1000)


> plot(density(data), xlim=c(-6,6), ylim=c(0,0.3))
> lines(density(data), xlim=c(-6,6), ylim=c(0,0.3))

# plot

> par(new=T)
> curve(truedensity, xlim=c(-6,6), ylim=c(0,0.3), col=2)
x

> plot(density(x))
> rug(x)
> rug(jitter(x, amount = .1), side = 3, col = "light blue")
density(x = x)

Density

0.10

0.15

0.00

0.00

0.05

0.05

0.10

truedensity
Density (x)

0.20

0.15

0.25

0.20

0.30

density(x = data)

N = 1000 Bandwidth
x
= 0.3965

density() bw

N = 1000 Bandwidth = 0.4056

17

167

bw

nrd0

()
1/5 1.34 0.9 (=

Silverman (1986) ) 0
bw > 0 (Silverman, B. W. (1986) Density Estimation.

London: Chapman and Hall.)


nrd

nrd0 Scott (1992) (Scott, D. W.


(1992) Multivariate Density Estimation: Theory, Practice, and Visualization. Wiley.)

ucv

bcv

SJ-ste

() Sheather & Jones

(1991) (Sheather, S. J. and Jones, M. C. (1991) A reliable


data-based bandwidth selection method for kernel density estimation. Journal of the
Royal Statistical Society series B, 53, 683-690.)
SJ-dpi

() Sheather & Jones (1991)

bw

adjust

bw adjust*bw

kernel window

gaussian rect-

angular triangular epanechnikov biweight cosine optcosine


epanechnikov
window=g
cosine S optcosine

width

S bw width
bw bw width

give.Rkern

TRUE canonical band-

width
n

from to

from to n1

cut

na.rm

TRUE x FALSE

generator() f (x) 1000 ( SJ )


density() *2

*2

KernSmooth dpik() bkde()

>
>
>
>

library(KernSmooth)
data <- generator(1000); h <- dpik(data)
est <- bkde(data, bandwidth=h)
plot(est, type="l", xlim=c(-6,6), ylim=c(0,0.3))

17

168

> curve(truedensity, xlim=c(-6,6), ylim=c(0,0.3), col=2)


> par(new=T)
> plot(density(data,bw="SJ"), xlim=c(-6,6), ylim=c(0,0.3), xlab="", ylab="")

0.15
0.00

0.05

0.10

truedensity (x)

0.20

0.25

0.30

density(x = data, bw = "SJ")

17.5
hist2d() (gregmisc)
bkde2D() (KernSmooth) kde2d() (MASS)

>

library(gregmisc)

Attaching package gregmisc:


The following object(s) are masked from package:base :
lowess
>

x <- rnorm(2000, sd=4)

# 2

>

y <- rnorm(2000, sd=1)

# (persp)
# hist2d()

>
>

h2d <- hist2d(x, y, show=FALSE, same.scale=TRUE, nbins=c(20,30))

>

persp( h2d$x, h2d$y, h2d$counts,

ticktype="detailed", theta=60, phi=30,

expand=0.5, shade=0.5, col="cyan", ltheta=-30)

>

library(MASS)

# width.SJ() MASS

>

library(KernSmooth)

# bkde2D() KernSmooth

>

x <- rnorm(2000, sd=4)

>

y <- rnorm(2000, sd=1)

>

f1 <- bkde2D(cbind(x, y), bandwidth=c(width.SJ(x), width.SJ(y)))

>

persp(f1$fhat, phi = 30, theta = 20, d = 5)

17

169

60

unts
h2d$co

40
20
0
10

d$
x

5
5

$y

h2

10

h2d

5
10

f1$fha

10

17.6 lowess()
lowess() lowess() x y
lines()

lowess(x, y, f=2/3, iter=3, delta=.01*diff(range(x)))


*3

x y

iter

iter lowess

delta

delta x lowess

> data(cars)
> plot(cars, main = "lowess(cars)")
> lines(lowess(cars), col = 2)
> lines(lowess(cars, f = 0.2), col = 3)
> legend(5, 120, c(paste("f = ", c("2/3", ".2"))), lty = 1, col = 2:3)

120

lowess(cars)

dist

20

40

60

80

100

f = 2/3
f = .2

10

15

20

25

speed

*3

Nadaraya-Watson ksmooth() 3
smooth.spline()Friedman SuperSmoother supsmu() runmed()
smooth() smoothEnds()

18

170

18

18.1
R
> ()

(x)

1 1 x

(x, y)

2 2 x, y

(y x)

x y

(A)

2 2 A

10 2 2
sleep

group1

0.7

group2

1.9

1.6

0.8

0.2

1.1

1.2

0.1

0.1
0.1

3.4

3.7

0.8

0.0

2.0

4.4

5.5

1.6

4.6

3.4

> group1 <- c(0.7,-1.6,-0.2,-1.2,-0.1,3.4,3.7,0.8,0.0,2.0)

# 1

> group2 <- c(1.9, 0.8, 1.1, 0.1,-0.1,4.4,5.5,1.6,4.6,3.4)

# 2

t t.test() sleep

18.1.1 (1) t
t.test() 1 t

> t.test(x, alternative=c("two.sided","less","greater"),


mu=0, paired=FALSE, var.equal=FALSE, conf.level=0.95)
1 t mu 0

95%

18

171

> t.test(group1, mu=0)


One Sample t-test
data:

group1

t = 1.3257, df = 9, p-value = 0.2176


alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
-0.5297804

2.0297804

sample estimates:
mean of x
0.75
mu 0

data

t = 1.3257

df = 9

p-value = 0.2176

p 0.05

alternative hypothesis

95 percent confidence interval

95% [0.5297804 2.0297804]

sample estimates

0.75

> t.test(group1, mu=65, alternative="greater")


One Sample t-test
data:

group1

t = -113.5692, df = 9, p-value = 1
alternative hypothesis: true mean is greater than 65
95 percent confidence interval:
-0.2870553

Inf

sample estimates:
mean of x
0.75

18.1.2 (2) t
1 2
t.test() t

> t.test(x, y, alternative=c("two.sided","less","greater"),


mu=0, paired=FALSE, var.equal=FALSE, conf.level=0.95)
t.test()

18

172

alternative=two.sided

alternative

alternative=greater

()

alternative=less

()

mu

paired

TRUE t

var.equal

TRUE 2

conf.level

t.test() *1

> t.test(group1, group2, var.equal=T)


Two Sample t-test
data:

group1 and group2

t = -1.8608, df = 18, p-value = 0.07919


alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-3.3638740

0.2038740

sample estimates:
mean of x mean of y
0.75

2.33

p p-value 0.07919 0.05

statistic

parameters

p.value

p 5% 0.05

95 percent confidence

95%

interval
estimate

null.value

alternative

method

data.name

*1

var.equal=T var.equal=F

18

173

18.2
18.2.1
stepfum ecdf() (cdf)

stepfun
> data <- rnorm(30)

> Fn <- ecdf(data)

# ecdf()

> Fn

> summary(Fn)

# Fn

> summary.stepfun(Fn)

# Fn

> plot(Fn)

> plot(Fn, do.point=F, verticals=T)

> x <- seq(-3,3,0.01)


> lines(x, pnorm(x, mean=mean(data), sd=sqrt(var(data))), col=2)

0.8
0.0

0.2

0.4

Fn(x)

0.6

0.8
0.6
Fn(x)
0.4
0.2
0.0

0.0

0.2

0.4

Fn(x)

0.6

0.8

1.0

ecdf(data)

1.0

ecdf(data)

1.0

ecdf(data)

Q-Q

qqnorm(x)

x
qqnorm()

qqline(x)

qqplot(x, y)

x y ( Quantile-Quantile PlotQ-Q )

qqplot lsfit() abline()

> x <- rt(50, df=5)


> xy <- qqplot(qt(ppoints(50), df=5), x)
> abline(lsfit(xy$x, xy$y), lty=2)
x

ppoints() QQ qlnorm() *2
> plot(qlnorm(ppoints(x)), sort(x))

*2

qlnorm()

174

2
0
2

sort(x)

18

qt(ppoints(50), df = 5)

10

qlnorm(ppoints(x))

18.2.2
shapiro.test() Shapiro-Wilk

> data(faithful)
> long <- faithful$eruptions[faithful$eruptions > 3]
#

> long

> shapiro.test(long)
Shapiro-Wilk normality test
data:

long

W = 0.9793, p-value = 0.01052


ks.test() Kolmogorov-Smirnov

> data(faithful)
> ( long <- faithful$eruptions[faithful$eruptions > 3] )

> ks.test(long, "pnorm", mean=mean(long), sd=sqrt(var(long)))


One-sample Kolmogorov-Smirnov test
data:

long

D = 0.0661, p-value = 0.4284


alternative hypothesis: two.sided

18.2.3
170

18.2.4
9 x y

> x <- c(1.83,

0.50,

1.62,

2.48, 1.68, 1.88, 1.55, 3.06, 1.30) # first

visit

> y <- c(0.878, 0.647, 0.598, 2.05, 1.06, 1.29, 1.06, 3.14, 1.29) # second visit

18

175

t
t

> t.test(x, y, paired = TRUE, alternative = "greater")


> t.test(y - x, alternative = "less")

Paired t-test
data:

x and y

t = 3.0354, df = 8, p-value = 0.008088


alternative hypothesis: true difference in means is greater than 0
95 percent confidence interval:
0.1673028

Inf

sample estimates:
mean of the differences
0.4318889

> wilcox.test(x, y, paired = TRUE, alternative = "greater")


> wilcox.test(y - x, alternative = "less")

Wilcoxon signed rank test


data:

x and y

V = 40, p-value = 0.01953


alternative hypothesis: true mu is greater than 0

18.3
170 sleep 1 2

t
t.test()

> t.test(group1, group2)


Welch Two Sample t-test
data:

group1 and group2

t = -1.8608, df = 17.776, p-value = 0.0794


alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-3.3654832

0.2054832

sample estimates:
mean of x mean of y
0.75

2.33

18

176

t
t *3 170 (y x)

> t.test(extra ~ group, data = sleep, var.equal=T) # extragroup


U
wilcox.test() U correct=F
*4

> wilcox.test(group1, group2)


Wilcoxon rank sum test with continuity correction
data:

group1 and group2

W = 25.5, p-value = 0.06933


alternative hypothesis: true mu is not equal to 0
F

170 sleep var.test() group1 group2


> var.test(group1, group2)
F test to compare two variances
data:

group1 and group2

F = 0.7983, num df = 9, denom df = 9, p-value = 0.7427


alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
0.198297 3.214123
sample estimates:
ratio of variances
0.7983426

2 3

*4

80

73

80

82

73

68

81

85

85

93

88

74

t 2

18

177

A B C 3
5%

bartlett.test()
> length <- c(80, 73, 80, 82, 74, 73, 68, 81, 85, 85, 93, 88)

> group

<- c(rep(1, 5), rep(2, 4), rep(3, 3))

> bartlett.test(length, group)


Bartlett test of homogeneity of variances
data:

length and group

Bartletts K-squared = 1.5451, df = 2, p-value = 0.4618

18.4
18.4.1 2 ()
chisq.test()

(1), (2) (3) (5) correct=F

(1) 1 c(8, 12, 10, 9, 5, 6)

(16 ) 1

(2) 1 c(20,8,5,2), p=c(4, 3, 2, 1)/10 35

ABOAB 40%30%20%10%

(3) 2 matrix(c(20, 15, 16, 4, 15, 7, 9, 4), ncol=2, byrow=T) 90


2

(4) 2 2 matrix(c(20, 15, 16, 9), ncol=2, byrow=T) 60


2 2

(5) m matrix(c(20, 15, ... ), ncol=m, byrow=T)

m (m2)

> chisq.test(c(8, 12, 10, 9, 5, 6))


> chisq.test(c(20,8,5,2), p=c(4, 3, 2, 1)/10)
> chisq.test(matrix(c(20, 15, 16, 4, 15, 7, 9, 4), ncol=4, byrow=T))
> chisq.test(matrix(c(20, 15, 16, 9), ncol=2, byrow=T))

18

178

> chisq.test(matrix(c(20, 15, 16, 4, 15, 7, 9, 4, 10), ncol=3, byrow=T))

18.4.2
2

14

22

17

21

18

25

43

> x <- matrix(c(14, 8, 4, 17), ncol=2, byrow=T)


> chisq.test(x)
Pearsons Chi-squared test with Yates continuity correction
data:

X-squared = 7.0406, df = 1, p-value = 0.007968


2
fisher.test() 2 2
> x <- matrix(c(14, 8, 4, 17), ncol=2, byrow=T)
> fisher.test(x)
Fishers Exact Test for Count Data
data:

p-value = 0.005089
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
1.567890 39.549785
sample estimates:
odds ratio
7.051895
( 2 2 )

2 2 2 2 ()

() 2 () 2

mcnemar.test() 2 2 correct=F

18

179

14

22

17

21

18

25

43

> x <- matrix(c(14, 8, 4, 17), ncol=2, byrow=T)


> mcnemar.test(x, correct=F)
McNemars Chi-squared test
data:

McNemars chi-squared = 1.3333, df = 1, p-value = 0.2482


( 2 2 )

() 2 () 2

300 245 250 157


prop.test()

correct=F *5
> prop.test(c(245, 157), c(300,250), correct=F)
2-sample test for equality of proportions without continuity
data:

correction

c(245, 157) out of c(300, 250)

X-squared = 24.6789, df = 1, p-value = 6.772e-07


alternative hypothesis: two.sided
95 percent confidence interval:
0.1144583 0.2628750
sample estimates:
prop 1

prop 2

0.8166667 0.6280000

10
1 5 5 1

*5

vcd summary(oddsratio(table(A,B),log=F))
log=F
prop.trend.test() prop.trend.test
( 1, 2)

18

180

(5 1)

1 *6
> x <- c(4, 1, 1, 2, 1, 2, 4, 3, 3, 2)
> y <- c(2, 1, 3, 1, 5, 1, 5, 3, 3, 1)
> binom.test(c(length(x[x>y]), length(x[x < y])))
Exact binomial test
data:

c(length(x[x > y]), length(x[x < y]))

number of successes = 4, number of trials = 7, p-value = 1


alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
0.1840516 0.9010117
sample estimates:
probability of success
0.5714286

A B A B

()
A

80

15

10

40

20

10

25

() vcd Kappa() *7
> measure2 <- matrix(c(80, 15,
+

5,

10, 40, 20,

5, 10, 25), 3, byrow=T)

*6

prop.test(
, , p = 0.5) binom.test()

binom.test(c(257, 243), p=1/2)

*7

# binom.test(, , )

() ICC (Intraclass correlation coefficient) irr icc()

> data(anxiety)
> icc(anxiety, model="twoway", type="agreement")

18

181

> Kappa(measure2)
value

ASE

lwr

upr

Unweighted 0.4915254 0.05492153 0.3838812 0.5991696

Weighted

0.4736842 0.08145561 0.3140342 0.6333343

18.4.3
2 x y cor.test()

> x <- c(70, 72, 62, 64, 71, 76, 60, 65, 74, 72)
> y <- c(70, 74, 65, 68, 72, 74, 61, 66, 76, 75)
method

pearson
kendall
spearman

> cor(x, y, method="spearman")


[1] 0.929878

> cor.test(x, y, method="pearson")

Pearsons product-moment correlation


data:

x and y

t = 8.5685, df = 8, p-value = 2.656e-05


alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.7957471 0.9883181
sample estimates:
cor

0.9496011

18.4.4
A B C 3

80

73

80

82

73

68

81

85

85

93

88

74

> length <- c(80,73,80,82,74,73,68,81,85,85,93,88)

> group

<- c( 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3)

18

182

gplots plotmeans()

*8

> library(gplots)

65

70

75

80

85

90

95

100

> plotmeans(length ~ group)

n=5

n=4

n=3

18.1

gplots plotCI()

> tmp

<- split(length, group)

> means <- sapply(tmp, mean)


> stdev <- sqrt(sapply(tmp, var))
> n

<- sapply(tmp, length)

> ciw

<- qt(0.975, n) * stdev / sqrt(n)

# length length()

> plotCI(x=means, uiw=ciw, col="black", barcol="blue", lwd=1)

oneway.test()

> oneway.test(length ~ group, var=T)

One-way analysis of means


data:

length and group

F = 4.7828, num df = 2, denom df = 9, p-value = 0.03845


*8

1 2 interaction.plot()

> attach(ToothGrowth)
> interaction.plot(dose, supp, len, fixed=TRUE)

18

183

kruskal.test() *9

> kruskal.test(length ~ group)


Kruskal-Wallis rank sum test
data:

length by group

Kruskal-Wallis chi-squared = 5.8408, df = 2, p-value = 0.05391

pairwise.t.test() 5%
holm bonferroni *10

> pairwise.t.test(length, group, p.adj = "bonf")


Pairwise comparisons using t tests with pooled SD
data:
1

length and group


2

2 1.000 3 0.074 0.059


P value adjustment method: bonferroni

A B C 3

10

20

30

40

180

193

200

201

150

189

186

190

144

178

166

173

5%

> x <- matrix(c(180,193,200,201,


+

150,189,186,190,

144,178,166,173), ncol=4, byrow=T)

*9

>
>
>
>

*10

x <- c(80, 73, 80, 82, 74)


y <- c(73, 68, 81, 85)
z <- c(85, 93, 88)
kruskal.test(x, y, z)

pairwise.wilcox.test()
TukeyHSD() multcomp simtest(x b, type=Williams)

18

184

> friedman.test(x)
Friedman rank sum test
data:

Friedman chi-squared = 7, df = 3, p-value = 0.0719

fligner.test()Fligner-Killeen
mantelhaen.test()Cochran-Mantelansari.test()Ansari-Bradley

Haenszel mood.test()Mood quade.test()Quade

18.5
R

power.t.test()

power.anova.test()

power.prop.test()

t power
sig.level type=c(two.sample, one.sample, paired) ,
alternative=c(two.sided, one.sided)

> power.t.test(n=100, delta=1.0, sd=2.5)


Two-sample t test power calculation
n = 100
delta = 1
sd = 2.5
sig.level = 0.05
power = 0.8036466
alternative = two.sided
NOTE: n is number in *each* group
power
1

> power.t.test(power=0.9, delta=1.0, sd=2.5)


Two-sample t test power calculation
n = 132.3106
delta = 1
sd = 2.5
sig.level = 0.05
power = 0.9
alternative = two.sided
NOTE: n is number in *each* group

19

185

19

19.1
lm() predict() trees

Girth
Height (
Volume 1
> plot(Volume ~ Girth, data = trees)

> result <- lm(Volume ~ Girth, data = trees)

> abline(result)

> summary(result)

Call:
lm(formula = Volume ~ Girth, data = trees)
Residuals:
Min

1Q

Median

3Q

Max

-8.0654 -3.1067

0.1520

3.4948

9.5868

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -36.9435

3.3651

Girth

0.2474

5.0659

-10.98 7.62e-12 ***


20.48

< 2e-16 ***

--Signif. codes:

0 *** 0.001 ** 0.01 * 0.05 . 0.1 1

Residual standard error: 4.252 on 29 degrees of freedom


Multiple R-Squared: 0.9353,

Adjusted R-squared: 0.9331

F-statistic: 419.4 on 1 and 29 DF,

p-value: < 2.2e-16

36.9435 5.0659

> new <- data.frame(Girth = seq(8, 24, 0.5))


> result.pre <- predict(result, new, interval="prediction")

> result.con <- predict(result, new, interval="confidence")

> matplot(new$Girth, cbind(result.pre, result.con), lty=c(1,2,2,3,3), type="l")

186

60
40

cbind(result.pre, result.con)

50
y
40
30
10

20

20

60

80

70

19

65

70

75

80

85

10

15

19.1

20

new$Girth

19.2

19.2 lsfit()
lsfit() y = X b + e b y X
() cbind
lsfit()

lsfit(x, y, wt=NULL, intercept=TRUE, tolerance=1e-07, yname=NULL)

wt

intercept

TRUE
FALSE

trees

> x <- trees$Height;

y <- trees$Volume

> z <- lsfit(x, y)

# z

> print(z)

# coefficients, residuals, intercept, qr

coef

intercept=T () 1

residuals

intercept

intercept

qr

x QR qt
t(Q)% *% y ( t(Q) Q ) qt qr

z *1
*1

ls.diag(z) H

19

187

> y - z$residuals
[1] 20.91087 13.19412 10.10742 23.99757 37.88772 40.97442 14.73747 28.62762
[9] 36.34437 28.62762 34.80102 30.17097 30.17097 19.36752 28.62762 27.08427
[17] 44.06112 45.60447 22.45422 11.65077 33.25767 36.34437 27.08427 23.99757
[25] 31.71432 37.88772 39.43107 36.34437 36.34437 36.34437 47.14782
R = () / ()

> sqrt(var(y - z$residuals)/var(y))


[1] 0.5982497
lsfit() abline()

> plot(x, y)

10

20

30

40

50

60

70

> abline(z, col=2)

65

70

75

80

85

19.3 lsfit()

19.3
lm()
*2

19.3.1 lm()
formula data

lm(formula, data, subset, weights, na.action,


method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
singular.ok = TRUE, contrasts = NULL, offset = NULL, ...)
*2

( )

19

188

formula

formula
yx

y = a + bx + ' ' y x

y x1 + x2

y = a + b1 x1 + b2 x2 + ' ' y
x1 , x2

y x1 x2

x1 : x2 y = a+b1 x1 +b2 x2 +b3 x1 x2 +'


' y x1 , x2

y x1 + x2 + x1 x2

y (x1 + x2)2

yx1

() + 0

y 1 + x + I(x2)

y = b0 + b1 x + b2 x2 + 'I(x2) poly(x,2)

yx|z

z y x

y . , data =

y x1 ,

y = a + b1 x1 + + ' ' y
y .

19.3.2
lm() obj

AIC(obj)

AIC

anova(obj1 , obj2)

coefficients(obj)

() coef(obj)

deviance(obj)

formula(obj)

logLik(obj)

plot(obj)

predict(obj, newdata=data.frame)

data.frame

print(obj)

residuals(obj)

() resid(obj)
df.residuals(obj)

step(obj)

AIC ()

summary(obj)

19

189

19.3.3
( 1) *3
> result <- lm(Volume ~ Girth, data = trees)

> summary(result)

( 2)
> result1 <- lm(log(Volume) ~ log(Girth), data = trees)
> summary(result1)
( 3) anova()
> anova(result1)
Analysis of Variance Table
Response: log(Volume)
Df Sum Sq Mean Sq F value
log(Girth)

1 7.9254

7.9254

Residuals

29 0.3832

0.0132

Pr(>F)

599.72 < 2.2e-16 ***

--Signif. codes:

0 *** 0.001 ** 0.01 * 0.05 . 0.1 1

> aov(result1)
Call:
aov(formula = result1)
Terms:
log(Girth) Residuals
Sum of Squares

7.925446

0.383244

29

Deg. of Freedom

Residual standard error: 0.1149578


Estimated effects may be unbalanced
( 4) result1 log(Height)

update()

> result1 <- lm(log(Volume) ~ log(Girth), data = trees)


> result2 <- update(result1, ~ . + log(Height), data = trees)
> summary(result2)

*3

lm() result result$fstatistic F p


F p

> result <- summary( result <- lm(Volume ~ Girth, data = trees) )
> f.stat <- result$fstatistic
> p.value <- 1-pf(f.stat["value"],f.stat["numdf"],f.stat["dendf"])
> p.value
value
0

19

190

Call:
lm(formula = log(Volume) ~ log(Girth) + log(Height), data = trees)
Residuals:
Min

1Q

Median

3Q

Max

-0.168561 -0.048488

0.002431

0.063637

0.129223

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -6.63162

0.79979

-8.292 5.06e-09 ***

log(Girth)

1.98265

0.07501

26.432

log(Height)

1.11712

0.20444

< 2e-16 ***

5.464 7.81e-06 ***

( 5) step() result2 1
AIC

> result3 <- step(result2)


Start:

AIC= -152.69

log(Volume) ~ log(Girth) + log(Height)


Df Sum of Sq
<none>

RSS

AIC

0.185 -152.685

- log(Height)

0.198

0.383 -132.185

- log(Girth)

4.628

4.813

-53.743

> summary(result3)
Call:
lm(formula = log(Volume) ~ log(Girth) + log(Height), data = trees)
Residuals:
Min

1Q

Median

3Q

Max

-0.168561 -0.048488

0.002431

0.063637

0.129223

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -6.63162

0.79979

-8.292 5.06e-09 ***

log(Girth)

1.98265

0.07501

26.432

log(Height)

1.11712

0.20444

< 2e-16 ***

5.464 7.81e-06 ***

( 6) . 1

> result <- lm(log(Volume) ~ .-1, data = trees)


> summary(result)
Call:
lm(formula = log(Volume) ~ . - 1, data = trees)
Residuals:
Median

3Q

Max

-0.188133 -0.072707 -0.001769

Min

1Q

0.062948

0.174312

19

191

Coefficients:
Estimate Std. Error t value Pr(>|t|)
Girth

0.144695

0.006381

22.68

< 2e-16 ***

Height 0.017830

0.001138

15.66 1.09e-15 ***

( 7) wle mle.cp()mle.aic()mle.cv() Cp
AIC

> result <- mle.cp(log(Volume) ~ log(Girth) + log(Height), data = trees)

# cp

> result <- mle.cv(log(Volume) ~ log(Girth) + log(Height), data = trees)

# CV

> result <- mle.aic(log(Volume) ~ log(Girth) + log(Height), data = trees) # AIC


> summary(result)
Call:
mle.aic(formula = log(Volume) ~ log(Girth) + log(Height), data = trees)
Akaike Information Criterion (AIC):
(Intercept) log(Girth) log(Height)

aic

[1,]

-64.560

[2,]

-36.700

[3,]

2.196

[4,]

169.000

[5,]

632.100

[6,]

976.300

[7,]

0 1158.000

Printed the first

best models

wle wle.cp()wle.aic()wle.cv()
Cp AIC

19.4
glm() *4
binomialpoissoninverse.gaussian
gaussian
Gammaquasi family

family

binomial

logit, probit, log, cloglog

gaussian

identity, log, inverse

Gamma

identity, inverse, log

inverse.gaussian

1/mu2, identity, inverse, log

poisson

identity, log, sqrt

quasi

logit, probit, cloglog, identity, inverse, log, 1/mu2, sqrt

p(x) =

*4

1 + exp{(0 + 1 x)}

termplot() nlme lme()

19

> b0 <- -3;


> p

192

b1 <- 0.5;

x <- seq(0, 10, 0.1)

<- 1/(1+exp(-b0+b1*x))

> mydata <- rbinom(length(x), 1, prob=p)


> result <- glm(mydata ~ 1+x, binomial(logit))
> summary(result)
Call:
glm(formula = mydata ~ 1 + x, family = binomial(logit))
Deviance Residuals:
Min

1Q

Median

3Q

Max

-0.28951

-0.16852

-0.09972

-0.05892

2.86202

Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept)

-3.1513

1.4901

-2.115

0.0344 *

-0.4216

0.4925

-0.856

0.3919

19.5
nls() *5

> f <- function(x) 1/(1+exp(-3-0.5*x))


> x <- seq(0,10,0.1);

y <- f(jitter(x, amount=0.2))

> ( result <- nls(y ~ a/(1+exp(-b-c*x)), start=c(a=2,b=1,c=0.1)) )


Nonlinear regression model
model:
data:
a

y ~ a/(1 + exp(-b - c * x))


parent.frame()
b

1.0000121 3.0203203 0.4931959

> predict.c <- predict(result)


> plot(x, y, ann=F, xlim=c(0,10), ylim=c(0.95,1));

par(new=T)

0.98
0.97
0.95

0.96

predict.c

0.99

1.00

> plot(x, predict.c, type="l", xlim=c(0,10), ylim=c(0.95,1))

6
x

*5

nlme nlme()

10

20

193

20

( library() )

20.1
v2 v1 v4 v3 v6 v5

> v1 <- c(1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,5,6); v2 <- c(1,2,1,1,1,1,2,1,2,1,3,4,3,3,3,4,6,5)


> v3 <- c(3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,5,4,6); v4 <- c(3,3,4,3,3,1,1,2,1,1,1,1,2,1,1,5,6,4)
> v5 <- c(1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,6,4,5); v6 <- c(1,1,1,2,1,3,3,3,4,3,1,1,1,2,1,6,5,4)
> m1 <- cbind(v1,v2,v3,v4,v5,v6)
> cor(m1)
v1

v2

v3

v4

v5

v6

v1 1.0000000 0.9393083 0.5128866 0.4320310 0.4664948 0.4086076


v2 0.9393083 1.0000000 0.4124441 0.4084281 0.4363925 0.4326113
v3 0.5128866 0.4124441 1.0000000 0.8770750 0.5128866 0.4320310
v4 0.4320310 0.4084281 0.8770750 1.0000000 0.4320310 0.4323259
v5 0.4664948 0.4363925 0.5128866 0.4320310 1.0000000 0.9473451
v6 0.4086076 0.4326113 0.4320310 0.4323259 0.9473451 1.0000000
> factanal(m1, factors=3) # varimax is the default
Call:
factanal(x = m1, factors = 3)
Uniquenesses:
v1

v2

v3

v4

v5

v6

0.005 0.101 0.005 0.224 0.084 0.005


#

Loadings:
Factor1 Factor2 Factor3
v1 0.944

0.182

0.267

v2 0.905

0.235

0.159

v3 0.236

0.210

0.946

v4 0.180

0.242

0.828

v5 0.242

0.881

0.286

v6 0.193

0.959

0.196

20

194

Factor1 Factor2 Factor3


SS loadings

1.893

1.886

1.797

Proportion Var

0.316

0.314

0.300

Cumulative Var

0.316

0.630

0.929

The degrees of freedom for the model is 0 and the fit was 0.4755
v2 v1 v4 v3 v6 v5

20.2
cancor()

> library(mva)
> data(LifeCycleSavings)
> pop <- LifeCycleSavings[, 2:3]
> oec <- LifeCycleSavings[, -(2:3)]
> cancor(pop, oec)

$cor

# ()

[1] 0.8247966 0.3652762


# x

$xcoef
[,1]

[,2]

pop15 -0.009110856 -0.03622206


pop75

0.048647514 -0.26031158
# y

$ycoef
[,1]

[,2]

[,3]

sr

0.0084710221

3.337936e-02 -5.157130e-03

dpi

0.0001307398 -7.588232e-05

4.543705e-06

ddpi 0.0041706000 -1.226790e-02

5.188324e-02
# x

$xcenter
pop15

pop75

35.0896

2.2930
# y

$ycenter
sr

dpi

ddpi

9.6710 1106.7584

3.7576

20.3
MASS lda()

predict.lda()
> library(MASS)
> data(iris3)
> Iris <- data.frame(rbind(iris3[,,1], iris3[,,2], iris3[,,3]),
+

Sp = rep(c("s","c","v"), rep(50,3)))

> train <- sample(1:150, 75)

20

> table(Iris$Sp[train])
c

195

# your answer may differ


#

25 25 25

# 22 23 30

> z <- lda(Sp ~ ., Iris, prior = c(1,1,1)/3, subset = train)


> predict(z, Iris[-train, ])$class
[1] s s s s s s s s s s s s s s s s s s s s s s s s s c c c c c c c c c c c c c
[39] c c v c c c c c c c c c v v v v v v v v v v v v v v v v c v v v v v v v v
Levels: c s v
MASS qda() predict.qda()

> data(iris3)
> tr <- sample(1:50, 25)
> train <- rbind(iris3[tr,,1], iris3[tr,,2], iris3[tr,,3])
> test <- rbind(iris3[-tr,,1], iris3[-tr,,2], iris3[-tr,,3])
> cl <- factor(c(rep("s",25), rep("c",25), rep("v",25)))
> z <- qda(train, cl)
> predict(z,test)$class
[1] s s s s s s s s s s s s s s s s s s s s s s s s s c c c c c c c c c c c c c
[39] c c c c c v c c c c c c v v v v v v v v v v v v v v v v v v c v v v v v v
Levels: c s v

20.4
prcomp()

> data(USArrests)
> prcomp(USArrests)
Standard deviations:
[1] 83.732400 14.212402

6.489426

2.482790

Rotation:
PC1

PC2

PC3

PC4

Murder

-0.04170432 -0.04482166

0.07989066

0.99492173

Assault

-0.99522128 -0.05876003 -0.06756974 -0.03893830

UrbanPop -0.04633575

0.97685748 -0.20054629

Rape

0.20071807

-0.07515550

0.05816914

0.97408059 -0.07232502

> prcomp(USArrests, scale = TRUE)


Standard deviations:
[1] 1.5748783 0.9948694 0.5971291 0.4164494
Rotation:
PC1

PC2

PC3

PC4

Murder

-0.5358995 -0.4181809

0.3412327 -0.64922780

Assault

-0.5831836 -0.1879856

0.2681484

0.74340748

UrbanPop -0.2781909

0.8728062

Rape

0.1673186 -0.8177779 -0.08902432

-0.5434321

0.3780158 -0.13387773

20

196

> plot(prcomp(USArrests))
> summary(prcomp(USArrests, scale = TRUE))
Importance of components:
PC1
Standard deviation

PC2

PC3

PC4

1.57 0.995 0.5971 0.4164

Proportion of Variance 0.62 0.247 0.0891 0.0434


Cumulative Proportion

0.62 0.868 0.9566 1.0000

20.5
hclust()

> data(USArrests)
> hc <- hclust(dist(USArrests), "ave")
> plot(hc)
> plot(hc, hang = -1)
> hc <- hclust(dist(USArrests)^2, "cen")
> memb <- cutree(hc, k = 10); cent <- NULL
> for(k in 1:10) cent <- rbind(cent, colMeans(USArrests[memb == k, , drop = FALSE]))
> hc1 <- hclust(dist(cent)^2, method = "cen" , members = table(memb))
> opar <- par(mfrow = c(1, 2))
> plot(hc, labels = FALSE, hang = -1, main = "Original Tree")
> plot(hc1, labels = FALSE, hang = -1, main = "Re-start from 10 clusters")
> par(opar)

Cluster Dendrogram

Original Tree

(1)

20000
Height

10000
0

5000

20.2

5000

Height

15000

20000

Florida
North Carolina
California
Maryland
Arizona
New Mexico
Delaware
Alabama
Louisiana
Illinois
New York
Michigan
Nevada
Alaska
Mississippi
South Carolina
Washington
Oregon
Wyoming
Oklahoma
Virginia
Rhode Island
Massachusetts
New Jersey
Missouri
Arkansas
Tennessee
Georgia
Colorado
Texas
Idaho
Nebraska
Kentucky
Montana
Ohio
Utah
Indiana
Kansas
Connecticut
Pennsylvania
Hawaii
West Virginia
Maine
South Dakota
North Dakota
Vermont
Minnesota
Wisconsin
Iowa
New Hampshire

1000
0

dist(USArrests)
hclust (*, "average")

20.1

10000

50

Height

15000

100

6000
5000
4000
3000
2000

Variances

Restart from 10 clusters

150

7000

prcomp(USArrests)

dist(USArrests)^2
hclust (*, "centroid")

20.3

(2)

k-means
> library(mva)
> x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
+

matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))

# 2D example

> cl <- kmeans(x, 2, 20)


> plot(x, col = cl$cluster)
> points(cl$centers, col = 1:2, pch = 8)

dist(cent)^2
hclust (*, "centroid")

20

197

20.6
R R (
)
THE R BOOK ()

ts()

as.ts()is.ts()

ts.union()

ts.intersection()

window()

diff()

diffinv()

filter()

lag()

acf()

aggregate()

nfrequency

ar()

AR ar.burg()

ar.yw()ar.mle()ar.ols()
arima()

ARIMA

arima.sim()
ARMAacf()

ARMA ARMAtoMA()

Box.test()

ccf()

decompose()

stl()

pacf()

(partial autocorrelations)

PP.test()

spectrum()

spec.ar() spec.pgram()

spec.taper()
cpgram()

lag.plot()

monthplot()

ts.plot()

ts.plot() *1

> library(ts)
> data(UKLungDeaths)
> ts.plot(ldeaths, mdeaths, fdeaths,
+

gpars=list(xlab="year", ylab="deaths", lwd=c(1:3), col=c(2:4)))

*1

plot()

20

198

20.7
aml

time
status
x

Maintained Nonmaintained

*2 survfit()

> library(survival)
splines

> MYDATA <- aml


> MYDATA$time2 <- Surv(MYDATA$time, MYDATA$status)

# time2 +

> ( result <- survfit(time2 ~ x, data=MYDATA) )

Call: survfit(formula = time2 ~ x, data = MYDATA)


n events median 0.95LCL 0.95UCL
x=Maintained

11

31

18

Inf

x=Nonmaintained 12

11

23

Inf

> summary(result)

> plot(result, col=c(1,2))

0.6

Maintained
Nonmaintained

0.4

2000

0.0

500

1000

0.2

1500

deaths

2500

3000

0.8

3500

1.0

4000

> legend(100, 0.8, c("Maintained","Nonmaintained"), col=c(1:5), lwd=1, bg="gray")

1974

1975

1976

1977

1978

1979

1980

50

100

150

year

20.4

20.5

survdiff() coxph() *3 R
( ) THE R BOOK ()
*2

Surv(, , ) 0123

*3 0 strata()

> coxph(time2 ~ x + strata(DEMOG) , data=MYDATA) #

20

199

20.8
() ( )

> library(modreg)
> data(cars)
> with(cars, {
+

plot(speed, dist)

lines(ksmooth(speed, dist, "normal", bandwidth=2), col=2)

lines(ksmooth(speed, dist, "normal", bandwidth=5), col=3)

})

> data(cars)
> attach(cars)
> plot(speed, dist, main = "data(cars)

&

smoothing splines")

> ( cars.spl <- smooth.spline(speed, dist) )


Call:
smooth.spline(x = speed, y = dist)
Smoothing Parameter

spar= 0.7801305

lambda= 0.1112206 (11 iterations)

Equivalent Degrees of Freedom (Df): 2.635278


Penalized Criterion: 4337.638
GCV: 244.1044
> lines(cars.spl, col = "blue")
> lines(smooth.spline(speed, dist, df=10), lty=2, col = "red")
> legend(5,120,c(paste("default [C.V.] => df =",round(cars.spl$df,1)),
"s( * , df = 10)"), col = c("blue","red"), lty = 1:2, bg=bisque)

120
dist

60

80

100

default [C.V.] => df = 2.6


s( * , df = 10)

20

40

60
40
20

dist

80

100

120

data(cars) & smoothing splines

10

15
speed

20

25

10

15
speed

20

25


[1] The R Projecthttp : //www.r project.org/
R
[2] S ()
[3] S - (1) - ()
[4] isac S http : //s.isac.co.jp/
( 3 ) S 9 R ()
R
[5] HPhttp : //www.is.titech.ac.jp/ mase/R.html
R
R
R
[6] R ( HP)http : //aoki2.si.gunma u.ac.jp/R/
Mac R

[7] HPhttp : //r.nakama.ne.jp/

[8] RjpWiki () http : //www.okada.jp.org/RW iki/index.php?RjpW iki


RjpWiki R Wiki Wiki

[9] RHTML ()http : //www.okada.jp.org/cgi bin/Rsearch/namazu.cgi/


R html
[10] R ()
R R

[11] ()
R R

[12] The R Book ()


R OS R R
1
[13] THE R Tips () PDF R
[14] () ()
R-Tips

R ( S-Plus )

[15] R ()
PDF GUI R R commander
R commander
PDF (05/08/08)

PDF
RjpWiki PDF

You might also like