In: Computer Science
Run the following R commends.
set.seed(2019) x = rnorm(100,mean=0, sd=2) y = rnorm(100,mean=0,
sd=20)
[NOTE: Do NOT use built-in functions which can directly solve the
problems.]
(1) Compute the means of values in the vectors x and y,
respectively. Which one is more close to zero? Explain the
reason.
(2) Compute the sample standard deviations of values in the vector
x and y, respectively.
(3) Find the index positions in x and y of the values between -5
and 5, respectively
1. Computing the mean value of vector x and y :
We know that the mean = sum of all elements in the array / length of the array.
For Example : Mean o values in array a = [1,2,3,4,5] is :
mean = (1+2+3+4+5) / 5 = 3
Let's solve the question using R :
#Given
set.seed(2019)
x = rnorm(100,mean=0, sd=2)
y = rnorm(100,mean=0, sd=20)
#Computin mean of x
mean_x = sum(x) / length(x) # here sum function add all element of the vector and length function fetch the length vector
#Computing the mean of y
mean_y = sum(y) / length(y)
#Printing the value of mean_x and mean_y
prinit(mean_x) # -0.146668
print(mean_y) #-3.404389
--> Here we get the mean of vector x close to zero because of the small standard deviation. A smaller standard deviation indicates that more of the data is clustered about the mean.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
2. Computing the standard deviation for vector x and y :
#Steps to Compute Standard Deviation :
#Here we will use the value of variable mean_x and mean_y
sd_x = sqrt(sum((x-mean_x)^2) / (length(x) - 1))
sd_y = sqrt(sum((y-mean_y)^2) / (length(y) - 1))
#printing the sd values of x and y
print(sd_x) #1.810907
print(sd_y) #19.7784
------------------------------------------------------------------------------------------------------------------------------------------------------------------
3. Finding the index for the value between -5 to 5 :
# simple code
which( x == x[ x>= -5 && x<=5])
# [x>= -5 && x<=5] will fetch the value between -5 to 5 from vector x
# We then compare the original array to the boolean indexed vector
# which function simply print the position of those vector
#Similarly for y
which( y == y[ y>= -5 && y<=5])
----------------------------------------------------------------------------------------------------------------------------------------------------------------------