-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathch8_exercise.Rmd
92 lines (76 loc) · 1.82 KB
/
ch8_exercise.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
---
title: "迴圈與流程控制 - 隨堂練習"
author: "Yao-Jen Kuo"
date: "`r Sys.Date()`"
output:
html_document:
self_contained: false
---
```{r, include=FALSE}
tutorial::go_interactive()
```
## 迴圈練習
以 for 迴圈印出 1:100 的每個數字一一印出,但是跳過 6 的倍數。使用 `%%` 運算子與 `next` 來幫助你。
```{r ex="for_loop", type="sample-code"}
# Create the vector of 1:100
my_vector <-
# Write your for loop here
for (i in my_vector) {
if (i ___ 6 == 0) {
___
}
print(i)
}
```
```{r ex="for_loop", type="solution"}
# Create the vector of 1:100
my_vector <- 1:100
# Write your for loop here
for (i in my_vector) {
if (i %% 6 == 0) {
next
}
print(i)
}
```
```{r ex="for_loop", type="sct"}
test_object("my_vector", incorrect_msg = "Did you assign `my_vector` correctly?")
test_output_contains("for (i in my_vector) {
if (i %% 6 == 0) {
next
}
print(i)
}", incorrect_msg = "Did you write the loop statement correctly?")
```
## 迴圈練習(2)
練習使用 `break` 把一到九月印出來。
```{r ex="break_exercise", type="sample-code"}
# Print built-in vector month.name
# Write a for loop with break statement to print out the first 9 months
for (i in ___) {
if (i == "___") {
break
}
print(i)
}
```
```{r ex="break_exercise", type="solution"}
# Print built-in vector month.name
month.name
# Write a for loop with break statement to print out the first 9 months
for (i in month.name) {
if (i == "October") {
break
}
print(i)
}
```
```{r ex="break_exercise", type="sct"}
test_output_contains("month.name", incorrect_msg = "Did you correctly print out `month.name`?")
test_output_contains("for (i in month.name) {
if (i == \"October\") {
break
}
print(i)
}", incorrect_msg = "Did you write the loop with break statement correctly?")
```