Answered step by step
Verified Expert Solution
Question
1 Approved Answer
use R language for Rstudio In the following exercises, use for loops to do your iteration Do NOT use the built in function sum) 1.
use R language for Rstudio
In the following exercises, use "for" loops to do your iteration Do NOT use the built in function "sum") 1. Use a "for" loop to evaluate the following sum, when .5 10 v-0 # initialize y to O #for loop to iterate over the values of i running from 0 through 10 { #y y + (some expresson here involving x) print(y) Your answer should be 1.999023 2. Use a for loop, and the built in function "sqrt", to do the following: loop over the elements of x-c(16,-9,9,4,-1,0) if the element x[i] is positive, print x i] and the square root of x[i] or else if x i] is negative, print("x[i] is negative") x= c ( 16,-9,9,4,-1,0) #for # if (condition print (c(someting, sqrt (something)) #else #print message here Your output should be equivalent to: 16 4 "X[i] is negative" 9 3 4 2 "xi is negative" 3. Use a "for" loop to iterate over the elements of a vector x, and increment a counter nodd when the element of x is odd. Then print the number of even and odd elements of x. Recall that an integer y is odd if y%%2-=1, and otherwise y is even Use the R commands below to generate a vector "x" of length 100 set.seed (10) x=sample ( 1 : 10, 100, replace=T) Then modify the following code nodd=0 #initialize the counter nodd, which counts the number of odd elements of x # for ( ) {increment nodd in the loop when the associated element of is odd} #neven- calculate neven using the length of x and nodd. paste("number of odd elements-",nodd) ## [1] "number of odd elements O" #paste("number of even elements ",neven) For this vector x, the number of odd elements should be 56 5. generate a random 5x5 matrix whose entries are the numbers 1,2, 25, but in random positions using the following code set.seed(27) #set the seed foY the random x-matrix (sample (1:25), byrow-T , ncol-6) # number generator 3 21 8 ##[2,] 9 2 1 24 4 ##[3,] 10 12 7 20 15 ##[4.] 22 14 18 23 11 ##[5,] 6 16 19 13 17 Then, using a pair of nested for loops, loop over the positions in the matrix x, and if the associated element of x is odd, replace the element by its negative #for loop involving i { # for loop involving j { #i,jJ-ifelse([i,jJ22 # elements ) -[i,j], something here for even #print (1) Your answer should be equivalent to -25-3 -21 8 -5 9 2-1 24 4 10 12 -7 20 -15 22 14 18 -23 -11 6 16 -19-13 -17
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started