Create a function that takes as input a data table and


R programming

It is possible to approximate the area of any two-dimensional shape using a Monte Carlo technique. To do this, we specify a region of known area that contains the shape, sample uniformly on that region, then multiply the known area by the fraction of the points that fall within the shape we're trying to measure. In this problem you'll write code to carry this out for a circle with radius equal to one. We can compare this to what we already know about the area of circles to see how well our approximation method performs.

(a) Write expressions in R to do the following:

• Create two vectors x and y of length 100, where each is sampled from the Uniform distribution with lower limit -1 and upper limit 1.

• Calculate the proportion of these for which the point (x, y) lies within the unit circle.

• Make a scatter plot of x and y, coloring the points differently depending on whether they're inside the unit circle or not.

• Multiply the proportion by 4 (the area of the square over which we're sampling) to approximate the area inside the circle.

(b) Now use your code from part (a) to write the following functions:

• Create a function that takes as input a positive integer n and two vectors, x and y of length n, and calculates the proportion of these for which the point (x, y) lies within the unit circle.

• Create a function that takes as input a data table and makes a scatter plot of x and y, coloring the points differently depending on whether they're inside the unit circle or not. You can assume that the data table you are inputting is glyph ready to make this plot.

• Create a function that takes as input a number and multiplies it by 4.

(c) Now use your functions from part (b) to create a function that takes arguments n (for sample size) and plotit (to indicate whether or not to make the plot) and returns the approximated area and optionally makes a plot depending on whether plotit is TRUE or FALSE. Give each argument a default value of your choosing.

(d) The replicate function takes an R expression and evaluates it a specified number of times. You can think of it as a very simplified for loop in which exactly the same code gets evaluated each time through the loop. Use this function to approximate the area of the circle 100 times, first for n=50 and then for n=500 and storing the results in two different vectors.

(e) Make two histograms (facetted by vector size) showing the results from part (c). Add a vertical line to the plot to indicate the true area. Give your plot appropriate axis names and titles and a nice readable theme.

Request for Solution File

Ask an Expert for Answer!!
Computer Engineering: Create a function that takes as input a data table and
Reference No:- TGS02912301

Expected delivery within 24 Hours