官术网_书友最值得收藏!

Nested loops in R

We can nest loops, as well as if statements, to perform some more complicated tasks. In this recipe, we will first define a square matrix and then write a nested for loop to print only those values where I = J, namely, the values in the matrix placed in (1,1), (2,2), and so on.

How to do it…

We first define a matrix in R using the following matrix() function:

mat= matrix(1:25, 5,5)

Now, we use the following code to output only those elements where I = J:

for (i in 1:5){
  for (j in 1:5){
    if (i ==j){
      print(mat[i,j])
    }
   }
}

The if statement is nested inside two for loop statements. As we have a matrix, we have to use two for loops instead of just one. The output of the matrix would be values such as 1, 7, 13, and 19.

主站蜘蛛池模板: 法库县| 肃宁县| 辽宁省| 马边| 凉城县| 宝鸡市| 东宁县| 比如县| 青阳县| 青浦区| 安龙县| 余姚市| 阿坝县| 平顺县| 清远市| 屯昌县| 大厂| 武冈市| 绵竹市| 梨树县| 通江县| 马边| 喀什市| 崇文区| 正蓝旗| 尉犁县| 库车县| 雅安市| 浦县| 丹棱县| 金川县| 郯城县| 宁陵县| 谷城县| 临清市| 彰武县| 廊坊市| 牟定县| 兴安县| 诸暨市| 洪雅县|