In: Computer Science
PLEASE USE R PROGRAMMING LANGUAGE TO ANSWER THESE EXAMPLES. Also please explain any important reasons/tips for how you coded. Thank you!
The Basic Examples:
a) If Statements: Write code that generates a random variable x uniformly between 0 and 1. If x is bigger than 0.6, square it; if x is less than 0.3, set it equal to 5, otherwise set x = 0.
b) Forloops: Write a program that makes a vector of all zeros of length 5.Then write a for loop that fills in this vector with the squares of the integers from 1 to 5. This for loop should iterate over the numbers 1 to 5, square each one, and enter the result in the vector. Show the results in your output/report.
c) Functions: Write a function that takes a number as an input and squares it (so the output is the square of the input number). Rewrite your code from part b) to use your new function, and run the updated code. Do your results match the results you got in part b)?
The program is as below
########
# Answer of part A
########
x = runif(1)
cat('The random value of x is :', x, '\n')
if (x > 0.6 ){
x = x*x
}else if(x < 0.3){
x = 5
}else x = 0
cat('value of x after conditional checking', x, '\n')
########
# Answer of part B
########
# define a vector v having 5 elements each one is 0
v = replicate(5, 0)
cat ('Initial value of vector v is: ', v,'\n')
#print(v)
for ( i in 1:5) {
v[i] = i*i
}
cat ('Final value of vector v is: ', v,'\n')
#print(v)
########
# Answer of part C
########
# User defined function
square.function <- function(a) {
result <- a * a
}
# initialize vector v with 0
v = replicate(5, 0)
for ( i in 1:5) {
v[i] = square.function(i)
}
cat ('Value of vector v using square function is: ', v,'\n')
#print(v)
Sample output:
The random value of x is : 0.2684412 value of x after conditional checking 5 Initial value of vector v is: 0 0 0 0 0 Final value of vector v is: 1 4 9 16 25 Value of vector v using square function is: 1 4 9 16 25
The output implies that result of part C is same as result of part B