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

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.

主站蜘蛛池模板: 获嘉县| 汤原县| 乌拉特前旗| 依兰县| 西昌市| 渭源县| 甘孜| 安溪县| 东辽县| 东乡| 大姚县| 准格尔旗| 田林县| 肇东市| 浮梁县| 陆丰市| 蚌埠市| 如皋市| 惠水县| 凤翔县| 右玉县| 苍山县| 亚东县| 手机| 滨州市| 施秉县| 司法| 平潭县| 辰溪县| 彭阳县| 抚远县| 三台县| 健康| 隆回县| 紫云| 乃东县| 绥棱县| 博罗县| 隆林| 嵩明县| 乌鲁木齐市|