14.1 Exercise 9: For loop

Create the script “exercise9.R” and save it to the “Rcourse/Module2” directory: you will save all the commands of exercise 9 in that script.
Remember you can comment the code using #.

correction

1- Write a for loop that iterates over 2 to 10 and prints the square root of each number (function sqrt()).

correction

## [1] 1.414214
## [1] 1.732051
## [1] 2
## [1] 2.236068
## [1] 2.44949
## [1] 2.645751
## [1] 2.828427
## [1] 3
## [1] 3.162278

2- Write a for loop that iterates over 5 to 15 and prints a vector of 2 elements containing each number and its square root

correction

## [1] 5.000000 2.236068
## [1] 6.00000 2.44949
## [1] 7.000000 2.645751
## [1] 8.000000 2.828427
## [1] 9 3
## [1] 10.000000  3.162278
## [1] 11.000000  3.316625
## [1] 12.000000  3.464102
## [1] 13.000000  3.605551
## [1] 14.000000  3.741657
## [1] 15.000000  3.872983

3- Create the following matrix

  • Write a for loop that iterates over each row of mat1 and prints the median value of each row.

correction

## [1] -0.4340862  1.0116672
## [1] 0.2887905
## [1] 0.1224976 0.3292072
## [1] 0.2258524
## [1] -2.534471 -1.672997
## [1] -2.103734
## [1] -0.2385856  0.9272744
## [1] 0.3443444
## [1] -1.463828  1.247498
## [1] -0.1081649
## [1] 0.8414449 0.7519016
## [1] 0.7966733
## [1]  1.0921350 -0.9161885
## [1] 0.08797323
## [1] -1.9674175 -0.4931046
## [1] -1.230261
## [1] -0.7141712 -0.6492121
## [1] -0.6816917
## [1] 1.0818456 0.2308486
## [1] 0.6563471
## [1] 1.2010953 0.6753097
## [1] 0.9382025
## [1] -1.0922622  0.4566863
## [1] -0.317788
## [1] -0.8439399  0.9427182
## [1] 0.04938917
## [1] -0.8756452 -0.1461592
## [1] -0.5109022
## [1]  1.068977 -1.177197
## [1] -0.05411016
## [1] -0.3181925  0.6704593
## [1] 0.1761334
## [1] -0.450344 -1.353209
## [1] -0.9017764
## [1] -1.142172 -1.018902
## [1] -1.080537
## [1] -0.1784857 -0.9767175
## [1] -0.5776016
## [1] 1.108961 1.121339
## [1] 1.11515