--- title: "Lab #1: Practice in R" output: pdf_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) set.seed(1) ``` The purpose of this lab is to get you comfortable working in R and trying a few things from the first lecture. ## Simulating data: We will simulate something like the weight vs. age data from a cubic function and add some noise and then apply a few methods. 1. Write a function in R to input the value (age) and output, “noise-free” weight: $f(x) = -0.0004x^3 + 0.025x^2 + 2x + 50$ ```{r} ``` 2. Next we will simulate some values for $x$. Use the sample function to generate a random sample of integers between 40 and 80 of size 1000 (you will need the replace=TRUE option to make sure the numbers can be resampled otherwise you will run out of values quickly). Don’t forget that you can type `?sample` to get help as to how to use the function. ```{r} ``` 3. Now generate a vector of the output of your function to generate the noise-free weights for each of the 1000 individuals. ```{r} ``` 4. Use `rnorm` to generate some normally distributed noise with mean 0.0 and sd of 10.0 for each of the values. ```{r} ``` 5. Add the noise-free weights to the noise to get your simulated outcome data. ```{r} ``` 6. Put these together in a dataframe with columns for age, weight (the observed outcome with noise), trueFx (the noise-free weight value), and noise. ```{r} ``` 7. Generate a plot of weight against age. ```{r} ``` ## Applying smoothing kernels: 1. Fit a nearest neighbors curve with ksmooth using a bandwidth of 10 and the `box` kernel. ```{r} ``` 2. Fit another curve this time using the `normal` kernel. ```{r} ``` 3. Plot the data with the two fitted curves and compare them. Hint: look at the object you have generated with ksmooth (i.e. type `name_of_the_object` or `print(name_of_the_object)`. Also, try `names(name_of_the_object)`. Use the command `lines` to plot the curves. ```{r} ``` 4. Fit another 2 curves with the "normal" kernel using bandwidths of size 5, 10, and 20. How do they compare? ```{r} ``` ## Fitting linear models: 1. Fit a linear regression to the data using the `lm` command. ```{r} ``` 2. Run `summary(your_linear_model_name)` to get an idea of the fit ```{r} ``` 3. Now fit quadratic and cubic models: you will need the `I` function to set quadratic and cubic terms in the regression, e.g. `I(x^2)` ```{r} ``` 4. Add the fitted models to the plots. For the linear model, use the `abline` command. For the polynomial fits, you can use the `curve` command (you will need the option `add = TRUE`). ```{r} ``` 5. Which curve do you prefer? How would you perform a hypothesis test for this? ```{r} ``` ## Practice installing an R package 6. R packages are easy to install using the `install.packages` command. Try installing the `e1071` package. We'll use this package later in the course for fitting support vector machines. ```{r} ```