Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

1. Please use R-programing to write the following code. Please show all steps, and outputs. Please also share you code and aswer all questions given

1. Please use R-programing to write the following code. Please show all steps, and outputs. Please also share you code and aswer all questions given in the format below.

```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ```

## Functions in R

### Debugging a function

a. In this problem, we will debug a function to compute the mean of each column of a matrix. We'll start by creating a *test suite*, a set of inputs where we know what the function should return, if it's working correctly.

Use the following code to create matrices to help you test the function. ```{r} test1 = matrix(1:9, nr = 3, nc = 3) test2 = matrix( c(3, 6, 1, 2), nr = 4, nc = 1 ) test3 = matrix(c(-1, 0, 1), nr = 1, nc = 3 ) ```

View the contents of `test1`, `test2`, and `test3`. ```{r}

```

**Write** 3 sentences describing what our function should return when it is applied to each of the matrices in the test suite, if the function is working correctly.

b. Evaluate the following cell to store the function `matrixMeans` in memory. ```{r} matrixMeans <- function(x){ # Computes the mean of each column of a matrix x. total = 0 count = 0 for(ii in 1:ncol(x)){ for(jj in 1:nrow(x)) total = total + x[ii, jj] count = count + 1 } return(total/count) }

```

b. Run the function `matrixMeans` 3 times, with each of `test1`, `test2`, and `test3` as its argument. ```{r}

``` ```{r}

```

```{r}

```

c. The results on the test suite demonstrate that the function `matrixMeans` is not working correctly. Let's begin by investigating the source of the error you got when analyzing `test2` and `test3`.

c1. Based on what the error message says, do you have any initial thoughts about where the problem is or what sort of problem it is? **Write your ideas here.**

- At this stage of the debugging process, it's fine if your answer is, "I have no clue!" But by reading the text of the error carefully, you can often make an educated guess. - By paying attention to error messages--and what you fixed to make them go away--you will gradually build your problem-solving skills in R and Python, making debugging faster and easier in the future.

c2. Open a web browser to a search engine. Type `R` and then copy the text of the error message.

- Sometimes it's helpful to copy the whole error message; other times it works better to copy just the portion after the `:`.

Read at least 2 of the webpages that come up in the search results. **Paste their URLs here.**

Based on what you read, **what ideas do you have** about what sort of problem this error message represents?

- If you have a specific idea about something to try fixing, proceed to part c4. - If you're unsure, do part c3 first.

c3. Based on the lines ` for(ii in 1:ncol(x)){` ` for(jj in 1:nrow(x))` what does `ii` represent?

What does `jj` represent?

Insert the line `print( paste("ii =", ii))` immediately after `for(ii in 1:ncol(x)){`. Evaluate the code cell containing the function again, and run the function with `test3` as input. What value of `ii` immediately precedes the error message?

Look at the line `total = total + x[ii, jj]`. How is the variable `ii` being used? Does this match what `ii` represents in the `for` loop?

c4. Change the code of the function to correct the issue that the error message is telling you about. Evaluate the code cell and run the function with `test3` as input. When you have successfully eliminated the error message, **explain** what change you made.

```{r} matrixMeans(test3) ```

d. Run the updated function on `test2`. ```{r}

``` **What problem** do you see with the output?

Insert print statements into the code to keep track of the values of `total` and `count`. Use the results to help you identify how to change the code. Edit the code. Then evaluate the code and run it on `test2` to verify that your correction worked.

```{r}

```

**Explain** what you changed and why.

e. Run the function on `test1` and `test3`. ```{r}

```

**What type** of object does `matrixMeans` return? A number, a vector, a data frame, something else, ...?

What type of object **should** `matrixMeans` return for the inputs `test1` and `test3`?

Modify the code so that `matrixMeans` returns a vector with the same length as the number of columns of its input. - The code `toReturn = numeric( ncol(x) )` creates an empty vector with length equal to the number of columns of `x`. - Use square bracket notation to set particular elements of `toReturn` equal to the desired output.

Run the function on `test1` and `test3` again to verify that the function now returns the a vector of the correct length.

```{r}

```

f. **Which elements** of the returned vectors are correct?

Depending on what changes you made in part d, you may need to make additional changes to the function to ensure that all elements of the returned vectors are correct. If so, focus on the results of the print statements that report the values of `total` and `count` to help you identify what changes to make. Run the function.

```{r}

```

When you have verified that the function is working correctly, **explain** what you changed and why.

### Creating your own function

In this problem, you will create your own function to combine values in a vector of numbers so that all entries in a *corresponding* vector are greater than or equal to a threshold. You will use this function on assignment 8.

a. Start by creating a test vector of numbers. ```{r}

```

Now, write a function that takes 2 arguments:

- a vector of numbers, and - a number `n` that tells how many elements of the vector to combine.

The function should return a vector where the first element is the sum of the first `n` elements of the input vector, and the rest of the vector is a copy of the other elements of the input vector. For example, if the input vector is `(2, 3, 6, 7, 8)` and `n = 2`, then the output should be the vector `(5, 6, 7, 8)`.

- Square bracket notation is likely to be helpful. For example, x[3:5] will return elements 3 through 5 of a vector `x`.

```{r}

```

Test your function on the test vector with at least 2 different values of `n`. If your function does not work correctly, go back and fix it.

```{r}

```

b. Next, write a function that analyzes the corresponding vector. This function should take 2 arguments: - a vector of non-negative numbers in increasing order, and - a threshold value. The threshold value should have a default value of 5.

The function should return `n`, the index of the last element of the vector that is less than the threshold. For example, if the input vector is `(0, 2, 4, 5, 7)` and the threshold is 5, then the function should return 3.

```{r}

```

c. Design a test suite. Your test suite should include

- a vector where all of the numbers are greater than or equal to 5, - a vector where the first number is less than 5 and the others are greater than or equal to 5, and - a vector with more than one number that is less than 5 and other numbers that are greater than or equal to 5.

Optional: For an extra challenge, include - a vector where all of the numbers are less than 5, and their sum is greater than or equal to 5, and - a vector where all of the numbers are less than 5, and their sum is less than 5.

All of the vectors in your test suite should have the numbers in **increasing order.** All of the numbers in your vectors should be non-negative.

```{r}

```

d. Use your test suite to test your function. Test it with both the default value of the threshold, and other values. Based on the results of your tests, make corrections to your function as needed.

```{r}

```

e. Create a function with the following arguments: - `x`, a vector to combine - `y`, a vector to use to determine which elements of `x` should be combined - a threshold value. The threshold value should have a default value of 5.

This function should call your function from part b to determine `n`, the number of elements of `y` that are less than the threshold. Then it should call your function from part a to combine the first `n` elements of `x`.

```{r}

```

f. Test your function from part e. Use the test vectors you created in part c as the `y` vectors. Make up your own vector(s) `x` of the same length as the `y` vectors. Based on the results of your tests, make corrections to your function as needed.

```{r}

```

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Navigating The Supply Chain Maze A Comprehensive Guide To Optimize Operations And Drive Success

Authors: Michael E Kirshteyn Ph D

1st Edition

B0CPQ2RBYC, 979-8870727585

More Books

Students also viewed these Databases questions

Question

Value statements of individual accountability

Answered: 1 week ago

Question

3. Define the attributions we use to explain behavior

Answered: 1 week ago