R question
Write a function to sort a dataframe using the alphabet order of its rownames. Test your function withmtcars dataset. Tips: use rownames() function to get the rownames.
Homework 3
Your name
Honor code:
“I have neither given nor received unauthorized assistance on this assignment.” Type your initials here.
I receive help from “” and give help to “”.
Problem
1
Write a function to sort a dataframe using the alphabet order of its rownames. Test your function with
mtcars dataset. Tips: use rownames() function to get the rownames.
Create an empty vector “mpg_discrete” with length equal to the number of rows in mtcars dataset. Write a
for loop to iterate i from 1 to the length of rows in mtcars dataset. Assign 0 to mpg_discrete[i] if the ith mpg
is larger or equal than its mean; Assign 1 to mpg_discrete[i] if the ith mpg is smaller than its mean.
Use apply function to avoid a for loop in problem 2 and create the same output. Tips: write a customized
function with input as a row vector and output as the converted mpg, i.e., 0 or 1.
Write a while loop to calculate pi with accuracy 0.00001 i.e. |yourestimatepi – pi|<0.00001 where pi is a default variable in R. Use Gregory-Leibniz series to estimate pi, i.e., pi = 4[ 1 - 1/3 + 1/5 -1/7 + 1/9 . . . ]. Tips: set a condition in while loop and let your loop iterate with n increasing and stop once the accuracy is achieved.
Set a random seed (use set.seed() function). Use the Monte Carlo method (See lecture note 9) to calculate
pi with the same accuracy as Problem 4. Compare the computational time of these two methods using
Sys.time() function. Use barplot to compare the computational time of two methods.
Write a customized function to calculate the sum of two vectors. The function should output an error
message if the vector does not have the same length. It also needs to output an error message if the
vectors are not numerical. Test the following myvecsum(c(1,2), c(2,3,4)); myvecsum(c(‘a’,‘b’), c(1,2));
myvecsum(c(1,2),c(2,3)).
1
- Problem 1
Problem 2
Problem 3
Problem 4
Problem 5
Problem 6