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

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.

主站蜘蛛池模板: 同仁县| 吴旗县| 长顺县| 达日县| 察隅县| 德令哈市| 兴义市| 马山县| 邵阳县| 孙吴县| 固镇县| 台安县| 昌吉市| 泸西县| 罗甸县| 巢湖市| 盘锦市| 凉城县| 宜昌市| 通榆县| 喜德县| 内乡县| 乌兰县| 左云县| 安阳市| 名山县| 平谷区| 文水县| 砀山县| 阿尔山市| 周口市| 双柏县| 会同县| 微博| 新巴尔虎右旗| 库伦旗| 墨脱县| 凭祥市| 镇雄县| 宣汉县| 孝昌县|