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

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.

主站蜘蛛池模板: 兖州市| 龙州县| 特克斯县| 会东县| 新邵县| 六枝特区| 高尔夫| 离岛区| 司法| 平谷区| 手机| 台山市| 张家川| 邹城市| 荆州市| 安丘市| 工布江达县| 康马县| 靖边县| 囊谦县| 红河县| 虎林市| 中卫市| 聂荣县| 万宁市| 桑日县| 辉县市| 依安县| 嫩江县| 浑源县| 扶绥县| 巴青县| 涡阳县| 杭锦后旗| 法库县| 大足县| 大连市| 马龙县| 治多县| 会昌县| 高阳县|