forked from TrevorFrench/R-for-Data-Analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2exercises.qmd
93 lines (66 loc) · 2.25 KB
/
p2exercises.qmd
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
93
# Exercises {.unnumbered}
## Questions
::: callout
## Exercise: 8-A
Create a data frame called "cars" that contains the first five rows of the mtcars dataset by using the "head" function. After printing to the console, you should get the following result:
``` r
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
```
:::
::: callout
## Exercise: 9-A
Write a function named "read_file" which will accept a file name as a parameter named "file_name". The function should then read in a csv with the specified name, store it as a data frame named "df", and return "df" as the final output.
:::
::: callout
## Exercise: 9-B
In exercise 9-A you created a function that will allow you to read a csv file. Extend this function by adding a second parameter named "csv" which will accept either "TRUE" or "FALSE". The functionality shouldn't change if the parameter is equal to "TRUE"; however, if the function is equal to "FALSE", the function should allow the user to read in an xlsx file instead.
For example, if a user wanted to read in a csv file they would use the function in this way:
``` r
read_file("iris.csv", TRUE)
```
If the user wanted to read in an xlsx file they would use the function in this way:
```r
read_file("iris.xlsx", FALSE)
```
:::
## Answers
::: callout
## Answer: 8-A
This task can be accomplished with the following code:
```{r}
cars <- head(mtcars, 5)
print(cars)
```
:::
::: callout
## Answer: 9-A
This task can be accomplished with the following code:
``` r
read_file <- function(file_name) {
df <- read.csv(file_name)
return(df)
}
```
:::
::: callout
## Answer: 9-B
Here's one way you could write your function to accomplish this task:
``` r
library(readxl)
read_file <- function(file_name, csv) {
if (csv == TRUE) {
df <- read.csv(file_name)
return(df)
}
if (csv == FALSE) {
df <- read_excel(file_name)
return(df)
}
}
```
:::