Exercises

Questions

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:

#                    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
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.

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:

read_file("iris.csv", TRUE)

If the user wanted to read in an xlsx file they would use the function in this way:

read_file("iris.xlsx", FALSE)

Answers

Answer: 8-A

This task can be accomplished with the following code:

cars <- head(mtcars, 5)
print(cars)
                   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
Answer: 9-A

This task can be accomplished with the following code:

read_file <- function(file_name) {
    df <- read.csv(file_name)
    return(df)
}
Answer: 9-B

Here’s one way you could write your function to accomplish this task:

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)
    }
}