-
Notifications
You must be signed in to change notification settings - Fork 10
/
ch9_exercise.Rmd
60 lines (46 loc) · 1.5 KB
/
ch9_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
---
title: "自訂函數 - 隨堂練習"
author: "Yao-Jen Kuo"
date: "`r Sys.Date()`"
output:
html_document:
self_contained: false
---
```{r, include=FALSE}
tutorial::go_interactive()
```
## 練習實作 R 既有的函數
練習實作 R 既有的函數 `max()`,它可以回傳一組向量中的最大值。
```{r ex="max_function", type="sample-code"}
# Declare my.max()
my.max <- function(input_vector) {
# Use sort() to sort input_vector with descending order and assign to sorted_vector
sorted_vector <- sort(input_vector, decreasing = ___)
# Return the first scalar of sorted_vector
return(___)
}
# Generate a vector
my_vector <- round(runif(10) * 100)
# Print my_vector out
# Call my.max() on my_vector
```
```{r ex="max_function", type="solution"}
# Declare my.max()
my.max <- function(input_vector) {
# Use sort() to sort input_vector with descending order and assign to sorted_vector
sorted_vector <- sort(input_vector, decreasing = TRUE)
# Return the first scalar of sorted_vector
return(sorted_vector[1])
}
# Generate a vector
my_vector <- round(runif(10) * 100)
# Print my_vector out
my_vector
# Call my.max() on my_vector
my.max(my_vector)
```
```{r ex="max_function", type="sct"}
test_function_definition("my.max", undefined_msg = "Did you correctly declare the function `my.max()`?")
test_output_contains("my_vector", incorrect_msg = "Did you print `my_vector` out?")
test_output_contains("my.max(my_vector)", incorrect_msg = "Did you call `my.max()` on `my_vector` correctly?")
```